首页 > 其他 > 详细

Combination Sum II

时间:2015-03-10 16:56:44      阅读:148      评论:0      收藏:0      [点我收藏+]

Combination Sum II

问题:

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

思路:

  常见的回溯问题

我的代码:

技术分享
public class Solution {
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        if(num == null || num.length == 0)    return rst;
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(num);
        helper(list, num, target, 0, 0);
        return rst;
    }
    private List<List<Integer>> rst = new ArrayList<List<Integer>>();
    public void helper(List<Integer> list, int[] candidates, int target, int sum, int start)
    {
        if(sum > target)    return;
        if(sum == target)
        {
            if(!rst.contains(list))
                rst.add(new ArrayList(list));
            return;
        }
        for(int i = start ; i < candidates.length; i++)
        {
            list.add(candidates[i]);
            helper(list, candidates, target, sum + candidates[i], i + 1);
            list.remove(list.size() - 1);
        }
    }
}
View Code

 

Combination Sum II

原文:http://www.cnblogs.com/sunshisonghit/p/4326331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!