40. Combination Sum II

和39. Combination Sum基本是一样的,就是上一次迭代的时候从这个数的位置开始,不可以重复的话,就从下一个位置开始

 1     public List<List<Integer>> combinationSum2(int[] candidates, int target) {
 2         List<List<Integer>> res = new ArrayList<List<Integer>>();
 3         if(candidates == null || candidates.length == 0) {
 4             return res;
 5         }
 6         Arrays.sort(candidates);
 7         helper(candidates, target, res, new ArrayList<Integer>(), 0, 0);
 8         return res;
 9     }
10     
11     public void helper(int[] candidates, int target, List<List<Integer>> res, List<Integer> item, int start, int curSum) {
12         if(curSum > target) {
13             return;
14         }
15         if(curSum == target) {
16             if(!res.contains(item)) {
17                 res.add(new ArrayList<Integer>(item));
18             }
19             return;
20         }
21         for(int i = start; i < candidates.length; i++) {
22             item.add(candidates[i]);
23             helper(candidates, target, res, item, i + 1, curSum + candidates[i]);
24             item.remove(item.size() - 1);
25         }
26         return;
27     }

基本无bug一遍通过的

posted @ 2016-02-28 08:47  warmland  阅读(119)  评论(0编辑  收藏  举报