本文已参与「新人创作礼」活动,一起开启掘金创作之路。
题目
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
题目解析
思路一
由于是寻找可能性,所以我们这里优先使用递归,先将数组排序,可以减少循环次数,如果当前值大于剩余target不在进行后面数的尝试,在升序中。避免重复组合的方法是,当前尝试的值,一定比我传过来的值大,因为前面是从小数开始尝试,一定组合过。属于区间范围的问题
var combinationSum = function (candidates, target) {
const arr = [];
candidates = candidates.sort((a, b) => a - b);
function fill(val, target, sumarr, charcode) {
if (target === 0) {
arr.push(sumarr);
return;
}
for (let i = 0, len = candidates.length; i < len; i++) {
if (candidates[i] < val) continue;
if (candidates[i] > target) break;
fill(candidates[i], target - candidates[i], [...sumarr, candidates[i]], charcode + String(candidates[i]).charCodeAt());
}
}
fill(0, target, [], 0);
return arr;
};
思路二
先设置一个底部位,即每一次只能搜索本位数字到后面的数字,避免了重复的出现,当累加sum大于target,此路不通,返回,当累加sum等于target,temp push进res中,跳出递归以后,要回溯,从temp中弹出数字。
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
const combinationSum = (candidates, target) => {
let res = [];
const dfs = (bottom,sum,temp) => {
if(sum > target) return;
if(sum === target) {
res.push([...temp]);
return;
}
for(let i = bottom;i < candidates.length;i++){
sum += candidates[i];
temp.push(candidates[i]);
dfs(i,sum,temp);
sum -= candidates[i];
temp.pop(candidates[i]);
}
}
dfs(0,0,[]);
return res;
};