40. 组合总和II
题目链接
dfs时防止重复
- 与上一题不同,这题中会有重复的数字,每个位置的数字只能使用一次(不同位置相同数字可以多次使用),且最终的结果不能有重复
- 因此需要先对candidates数组排序,dfs的时候,如果当前项和上一项相同就跳过
- 每次进入dfs,直接找下一个位置的数字
class Solution {
List<List<Integer>> ans;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
ans = new ArrayList<>();
dfs(candidates, target, new ArrayList<Integer>(), 0);
return ans;
}
private void dfs(int[] candidates, int target, List<Integer> now, int k){
if(target == 0){
ans.add(new ArrayList<Integer>(now));
return;
}
for(int i = k; i < candidates.length; i++){
if(i > k && candidates[i] == candidates[i-1])
continue;
target -= candidates[i];
if(target >= 0){
now.add(candidates[i]);
dfs(candidates, target, now, i+1);
now.remove(now.size() - 1);
}
target += candidates[i];
}
}
}