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

40. Combination Sum II

时间:2016-02-28 09:47:23      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

和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一遍通过的

40. Combination Sum II

标签:

原文地址:http://www.cnblogs.com/warmland/p/5224044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!