题目描述
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
题解
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> tmp = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
boolean[] used = new boolean[candidates.length];
Arrays.sort(candidates);
backtracking(0, candidates, target, used);
return res;
}
public void backtracking(int start, int[] candidates, int target, boolean[] used) {
if(target == 0) {
res.add(new ArrayList(tmp));
return;
}
for(int i = start; i < candidates.length && target > 0; i++) {
if(used[i]) {
continue;
}
if(i - 1 >= start && candidates[i] == candidates[i - 1] && !used[i - 1]) {
continue;
}
tmp.add(candidates[i]);
used[i] = true;
backtracking(i, candidates, target - candidates[i], used);
tmp.remove(tmp.size() - 1);
used[i] = false;
}
}
}