39. Combination Sum

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

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