Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
和之前一些题方法类似,DFS
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(candidates);
helper(ans, new ArrayList(), candidates, 0, target);
return ans;
}
private void helper(List<List<Integer>> ans, List<Integer> list, int[] candidates, int start, int target){
if(target==0){
ans.add(new ArrayList(list));
return;
}else if(target<0){
return;
}
for(int i=start; i<candidates.length; i++){
if(i>start && candidates[i]==candidates[i-1]) continue;
list.add(candidates[i]);
helper(ans, list, candidates, i+1, target-candidates[i]);
list.remove(list.size()-1);
}
}
}