class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(0, candidates, target, 0);
return res;
}
public void backtracking(int sum,int[] candidates,int target,int startIndex){
if(sum == target){
res.add(new ArrayList<>(path));
return;
}else{
for(int i = startIndex; i < candidates.length && candidates[i] + sum <= target;i++){
if(i > startIndex && candidates[i] == candidates[i - 1]) continue;
path.addLast(candidates[i]);
backtracking(sum + candidates[i], candidates, target, i + 1);
path.pollLast();
}
}
}
}
同一层的相同元素不纳入递归,因为这一层的相同元素比如1,1,2,中间的1会在第一个1的下层遍历中出现,可以选择选与不选,仍然可以囊括所有情况,如果中间的1保留,如果target=3,会出现2个相同组合。
这题有点绕。。