首页 > 其他 > 详细

39. Combination Sum

时间:2016-02-28 08:39:07      阅读:125      评论:0      收藏:0      [点我收藏+]

Backtracking问题

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

时间复杂度是指数级的,exponential

39. Combination Sum

原文:http://www.cnblogs.com/warmland/p/5224037.html

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