Combination Sum

题目:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 

[2, 2, 3]

题解

还是老问题,用DFS找解决方案,不同点是,这道题: The same repeated number may be chosen from C unlimited number of times.

所以,每次跳进递归不用都往后挪一个,还可以利用当前的元素尝试。

同时,这道题还要判断重复解。用我之前介绍的两个方法:

 1.       if(i>0 && candidates[i] == candidates[i-1])//deal with dupicate
                 continue; 

 2.       if(!res.contains(item)) 
                res.add(new ArrayList<Integer>(item));   

这两个方法解决。 

代码如下:

 1 public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {  
 2         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();  
 3         ArrayList<Integer> item = new ArrayList<Integer>();
 4         if(candidates == null || candidates.length==0)  
 5             return res; 
 6             
 7         Arrays.sort(candidates);  
 8         helper(candidates,target, 0, item ,res);  
 9         return res;  
10     }  
11     
12     private void helper(int[] candidates, int target, int start, ArrayList<Integer> item,   
13     ArrayList<ArrayList<Integer>> res){  
14         if(target<0)  
15             return;  
16         if(target==0){  
17             res.add(new ArrayList<Integer>(item));  
18             return;  
19         }
20         
21         for(int i=start;i<candidates.length;i++){  
22             if(i>0 && candidates[i] == candidates[i-1])//deal with dupicate
23                 continue;  
24             item.add(candidates[i]);
25             int newtarget = target - candidates[i];
26             helper(candidates,newtarget,i,item,res);//之所以不传i+1的原因是:
27                                                     //The same repeated number may be 
28                                                     //chosen from C unlimited number of times.
29             item.remove(item.size()-1);  
30         }  
31     }

reference: http://www.cnblogs.com/springfor/p/3884294.html

原文地址:https://www.cnblogs.com/hygeia/p/4643922.html