给定一个候选人编号的集合 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]
]
题解
- 回溯+剪枝
- 参考力扣39题
- 需要去重
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function(candidates, target) {
candidates.sort((a, b) => a - b);
let res = [];
let step = [];
const dfs = (index, target) => {
if(target == 0) {
res.push(step.slice());
return;
}
for(let i = index; i < candidates.length; i++) {
if(i > index && candidates[i] == candidates[i - 1]) continue; // 剪枝,去除重复的组合
if(target - candidates[i] < 0) return; // 剪枝
else {
step.push(candidates[i]);
dfs(i+1, target - candidates[i]);
step.pop(candidates[i]);
}
}
}
dfs(0, target);
return res;
};
本文解析了一道经典的算法题目——组合求和II,通过回溯算法加剪枝的方法解决了给定候选数字集合与目标数字,寻找所有可能的组合使得组合内数字之和等于目标数字的问题,并且确保组合不重复。
640

被折叠的 条评论
为什么被折叠?



