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]
]
Note:
combinationSum2(ans, candidates, target-candidates[i], i+1, list);
use i+1
to control duplicate selection.
if(i>start && candidates[i]==candidates[i-1]) continue;
use i>start
instead of i>0
to include the case when candidates has duplicate numbers.
Solution:
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> ans = new ArrayList<>();
combinationSum2(ans, candidates, target, 0, new ArrayList<Integer>());
return ans;
}
public void combinationSum2(List<List<Integer>> ans, int[] candidates, int target, int start, List<Integer> list){
if(target==0){
ans.add(new ArrayList<>(list));
return;
}
for(int i=start; i<candidates.length; i++){
if(i>start && candidates[i]==candidates[i-1]) continue;
if(target-candidates[i]<0) break;
list.add(candidates[i]);
combinationSum2(ans, candidates, target-candidates[i], i+1, list);
list.remove(list.size()-1);
}
}
}