码迷,mamicode.com
首页 > 其他好文 > 详细

Combination Sum II

时间:2015-03-10 16:59:16      阅读:153      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!