携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第18天,点击查看活动详情
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
解题思路
1. 给定的数组可能有重复的元素,先排序,使得重复的数字相邻,方便去重
2. for 枚举出选项时,加入下面判断,从而忽略掉同一层重复的选项,避免产生重复的组合。比如[1,2,2,2,5],选了第一个 2,变成 [1,2],它的下一选项也是 2,跳过它,因为如果选它,就还是 [1,2]
3. 当前选择的数字不能和下一个选择的数字重复,给子递归传i+1,避免与当前选的i重复
代码实现
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function (candidates, target) {
let res = [];
/**
*
* @param {*} index 当前开始的索引
* @param {*} path 回溯的路径
* @param {*} sum 当前路径中所有元素的和
*/
const backtrack = (index, path, sum) => {
// 和已超目标值 不符合退出
if (sum > target) return;
// 找到目标和 将路径加入结果集中
if (sum == target) return res.push(path.slice());
for (let i = index; i < candidates.length; i++) {
// 当前元素跟上一个元素相同且上一个元素在索引选择范围内则当前元素就不需要加入
if (i - 1 >= index && candidates[i - 1] == candidates[i]) continue;
// 选择 candidates[i]
path.push(candidates[i]);
sum += candidates[i];
// 递归遍历下一层回溯树 注意这里是i+1 因为同一个元素不能重复使用
backtrack(i + 1, path, sum);
// 撤销选择 candidates[i]
sum -= candidates[i];
path.pop();
}
};
// 先将数组升序排列
candidates.sort((a, b) => a - b);
backtrack(0, [], 0);
return res;
};
如果你对这道题目还有疑问的话,可以在评论区进行留言;