题目链接:https://leetcode.cn/problems/combination-sum-ii/
方法一 回溯
1 方法思想
2 代码实现
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
// boolean[] usedNums = new boolean[candidates.length];
combine(target, 0, 0, candidates, null);
return result;
}
public void combine(int target, int sum, int startIndex, int[] candidations, boolean[] usedNums) {
if (sum == target) {
result.add(new ArrayList<>(path));
return;
}
for (int i = startIndex; i < candidations.length; i++) {
if ((sum + candidations[i]) > target) break;
if (i > startIndex && candidations[i] == candidations[i - 1] ) continue;
// if (startIndex != 0 && candidations[i] == candidations[i - 1] && usedNums[i - 1]) break;
path.add(candidations[i]);
// usedNums[i] = true;
combine(target, sum + candidations[i], i + 1, candidations, usedNums);
path.remove(path.size() - 1);
}
}
}
3 复杂度分析
时间复杂度:
空间复杂度: