39. Combination Sum
Given a set of candidate numbers (C)(without duplicates)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.
- The solution set must not contain duplicate combinations.
For example, given candidate set[2, 3, 6, 7]and target7,
A solution set is:
[
[7],
[2, 2, 3]
]
思路: 递归
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> listResult = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
Arrays.sort(candidates);
backtrack(listResult,temp,candidates,0,0,target);
return listResult;
}
public void backtrack(List<List<Integer>> listResult,List<Integer> temp, int[] arr, int sum, int start, int target){
if (sum==target){
listResult.add(new ArrayList<>(temp));
}else if(sum>target){
return;
}else{
for (int i=start;i<arr.length;i++){
temp.add(arr[i]);
backtrack(listResult,temp,arr,sum + arr[i],i,target);
temp.remove(temp.size()-1);
}
}
}
}