Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
if(candidates==null||candidates.length==0){
return result;
}
List<Integer> subset=new ArrayList<>();
Arrays.sort(candidates);
helper(candidates,0,subset,target,result);
return result;
}
//递归的定义:在result[startIndex:]中选取和为target的组合,放在subset中,然后整个放到result里
private void helper(int[] candidates,int startIndex,List<Integer> subset,int target,List<List<Integer>> result){
if(target==0){
result.add(new ArrayList<>(subset));
return;
}
//递归的拆解
for(int i=startIndex;i<candidates.length;i++){
if(i!=0&&candidates[i]==candidates[i-1]){
continue;
}
if(target<candidates[i]){
break;
}
subset.add(candidates[i]);
helper(candidates,i,subset,target-candidates[i],result);
subset.remove(subset.size()-1);
}
}
}