算法学习记录(九十九)

76 阅读1分钟

39. 组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

image.png

解:

  1. 这题包含了一个隐藏条件,candidates其实是正整数数组,因为有负数和零可能会死循环。
  2. 递归函数的参数含义为idx:当前选择candidates的第几个数,sel:之前选择的集合,sum:之前的累加和
  3. 当idx越界,返回。当sum等于target表明成功。sum大于target表示失败返回。
  4. 排除了0和负数的干扰后就比较简单,对于candiadates的每一项而言,可以选择不选这个数(idx + 1继续递归),也可以选择这个数(idx不变,sel和sum加上这个数继续递归)
const combinationSum = function(candidates, target) {
    const res = []
    const getRes = (idx, sel, sum) => {
        if (idx === candidates.length) {
            return
        }
        if (sum === target) {
            res.push(sel)
            return
        }
        if (sum > target) return
        getRes(idx + 1, sel, sum)
        getRes(idx, [...sel, candidates[idx]], sum + candidates[idx])
    }
    getRes(0, [], 0)
    return res
};