创见博客
组合总和
七崽爱吃小饼干2026/01/15阅读 0专栏 算法合集

组合总和

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

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

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

示例 1:

codeType
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

codeType
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

codeType
输入: candidates = [2], target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

解法

解法一
ts
function combinationSum(candidates: number[], target: number): number[][] {
    const n = candidates.length
    // 把candidates按升序进行排列
    candidates.sort((a, b) => a - b)
    const res: number[][] = []
    const backtrack = (lastIndex:number, path: number[], sum: number) => {
        if(sum === target){
            res.push([...path])
            return
        }
        // target - sum就是差值,选择的数字从<=差值的数字中选就行
        // candidates是升序排列的,所以碰到不满足的数字,其之后的数字也都不满足。
        // 因为数字可以重复,所以没法原地修改数组
        // i也别从0开始,不然会出现重复序列,可以从答案的最后一个序列开始
        // 只要让得到的序列都是升序的,就不会有重复序列
        let i = lastIndex
        while(candidates[i] <= target - sum){
            backtrack(i, [...path, candidates[i]], sum + candidates[i])
            i++
        }
    }
    backtrack(0, [], 0)
    return res
};
解法二

优化了之前的重复创建path数组的步骤,在每次递归结束以后进行pop,把path数组回溯

ts
function combinationSum(candidates: number[], target: number): number[][] {
    const n = candidates.length
    // 把candidates按升序进行排列
    candidates = candidates.sort((a, b) => a - b)
    const res: number[][] = []
    const backtrack = (lastIndex:number, path: number[], sum: number) => {
        if(sum === target){
            res.push([...path])
            return
        }
        // target - sum就是差值,选择的数字从<=差值的数字中选就行
        // candidates是升序排列的,所以碰到不满足的数字,其之后的数字也都不满足。
        // 因为数字可以重复,所以没法原地修改数组
        // i也别从0开始,不然会出现重复序列,可以从答案的最后一个序列开始
        // 只要让得到的序列都是升序的,就不会有重复序列
        let i = lastIndex
        while(candidates[i] <= target - sum){
            const cur = candidates[i]
            // 递归前:选择当前元素,加入路径
            path.push(cur)
            sum += cur;
            // 递归处理下一层
            backtrack(i, path, sum);
            // 递归后:撤销选择,移出路径(回溯核心,恢复现场)
            sum -= cur;
            path.pop();
            i++
        }
    }
    backtrack(0, [], 0)
    return res
};
评论
0/100