代码(树层去重)
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used = new boolean[100]; // used默认值是false
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(candidates, target, 0, 0);
return res;
}
public void backtracking(int[] candidates, int target, int sum, int startIndex) {
if (sum == target) {
res.add(new ArrayList<>(path));
}
for (int i = startIndex; i <= candidates.length - 1 && used[i] == false && sum + candidates[i] <= target; i ++) {
if (i > startIndex && candidates[i] == candidates[i - 1]) continue;
sum += candidates[i];
path.add(candidates[i]);
used[i] = true;
backtracking(candidates, target, sum, i + 1);
used[i] = false;
path.remove(path.size() - 1);
sum -= candidates[i];
}
}
}
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
//boolean[] used = new boolean[100]; // used默认值是false
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
backtracking(candidates, target, 0, 0);
return res;
}
public void backtracking(int[] candidates, int target, int sum, int startIndex) {
if (sum == target) {
res.add(new ArrayList<>(path));
}
for (int i = startIndex; i <= candidates.length - 1; i ++) {
if (i > startIndex && candidates[i] == candidates[i - 1]) continue;
if (sum + candidates[i] <= target) {
sum += candidates[i];
path.add(candidates[i]);
//used[i] = true;
backtracking(candidates, target, sum, i + 1);
//used[i] = false;
path.remove(path.size() - 1);
sum -= candidates[i];
}
}
}
}
跳过同一树层使用过的元素
if (i > startIndex && candidates[i] == candidates[i - 1]) {
continue;
}