题目
和上一题的差别在于每个数字只能被使用一次,因此需要考虑去重的问题。而测试用例又对时间要求比较严格,所以需要用比较高效的去重方法。
描述
给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用 一次 。
注意:解集不能包含重复的组合。
链接:
https://leetcode.cn/problems/combination-sum-ii/description/
这道题的解法是参考官方题解写出的。
思路
- 使用试探-回溯法对答案进行搜索
- 预先收集每个candidate的数量,在回溯的时候统一处理
- 对于已经超出总和的情况做剪枝
复杂度
- 时间复杂度: O(2^n∗n)
- 空间复杂度: O(n)
代码
function combinationSum2(candidates: number[], target: number): number[][] {
candidates.sort((a, b) => a - b);
const result: number[][] = [];
const res: number[] = [];
const countMap = new Map<number, number>();
// 收集个数
const collectCount = () => {
for (const c of candidates) {
if (!countMap.has(c)) {
countMap.set(c, 1);
} else {
countMap.set(c, countMap.get(c) + 1);
}
}
}
collectCount();
const mapArray = [...countMap.keys()];
const backtrack = (left: number, index: number) => {
if (left === 0) {
result.push([...res]);
return;
}
const n = mapArray[index];
if (index === mapArray.length || left < n) return;
const count = countMap.get(n);
// 不选这个数
backtrack(left, index + 1);
const most = Math.min(count, Math.floor(left / n));
// 选1到most次这个数
for (let i = 1; i <= most; i++) {
res.push(n);
backtrack(left - i * n, index + 1);
}
// 逐次恢复
for (let i = 0; i < most; i++) {
res.pop();
}
}
backtrack(target, 0);
return result;
};