# [40] 组合总和 II
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
示例 1:
输入:candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[ [1,1,6], [1,2,5], [1,7], [2,6] ]
示例 2:
输入:candidates = [2,5,2,1,2], target = 5,
输出:
[ [1,2,2], [5] ]
提示:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
这题相比[39] 组合总和
来说,多了个每个数字在每个组合中只能使用一次
的条件,因此我们也针对这一点进行更改即可。
我们在选择时需要忽略掉同一层重复的元素,避免产生重复的组合。那么该如何做呢?
受到 [90] 子集 II
的启发,我们可以先将集合进行排序,这样通过与相邻节点比对就能判断是否有重复值存在了。此时进行剪枝即可。
function combinationSum2(candidates: number[], target: number): number[][] {
candidates.sort((a, b) => a - b);
const res: number[][] = [];
let currSum = 0;
backtrack([], 0);
return res;
function backtrack(path: number[], start: number) {
if (currSum === target) {
res.push([...path]);
return;
}
if (currSum > target) {
return;
}
for (let i = start; i < candidates.length; i++) {
if (i > start && candidates[i] === candidates[i - 1]) {
continue;
}
// 做选择
path.push(candidates[i]);
currSum += candidates[i];
// 回溯
backtrack(path, i + 1);
// 撤销选择
currSum -= candidates[i];
path.pop();
}
}
}