LeetCode 第39题:组合总和

126 阅读3分钟

LeetCode 第39题:组合总和

题目描述

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

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

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

难度

中等

题目链接

点击在LeetCode中查看题目

示例

示例 1:

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

示例 2:

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

示例 3:

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

提示

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

解题思路

方法:回溯算法

这是一道典型的回溯算法题目,需要考虑如何避免重复组合。

关键点:

  1. 使用回溯法枚举所有可能的组合
  2. 通过排序和剪枝优化搜索过程
  3. 同一个数字可以重复使用,但要避免重复组合

具体步骤:

  1. 对数组进行排序,方便剪枝
  2. 使用回溯法搜索所有可能的组合:
    • 记录当前已选数字和
    • 从当前位置开始尝试每个数字
    • 当和等于目标值时保存结果
    • 当和超过目标值时剪枝
  3. 返回所有有效组合

时间复杂度:O(n^(target/min)),其中min是数组中的最小值 空间复杂度:O(target/min),递归栈的深度

图解思路

回溯树分析表

层级当前和可选数字选择剩余目标
00[2,3,6,7]25
12[2,3,6,7]23
24[2,3,6,7]30
回溯2[2,3,6,7]32
回溯0[2,3,6,7]70

剪枝策略示意图

当前和下一个数字是否剪枝原因
565+6>7
474+7>7
232+3<7
020+2<7

代码实现

public class Solution {
    private IList<IList<int>> result = new List<IList<int>>();
    private List<int> current = new List<int>();
  
    public IList<IList<int>> CombinationSum(int[] candidates, int target) {
        Array.Sort(candidates); // 排序以便剪枝
        Backtrack(candidates, target, 0);
        return result;
    }
  
    private void Backtrack(int[] candidates, int remain, int start) {
        if (remain == 0) {
            result.Add(new List<int>(current));
            return;
        }
      
        for (int i = start; i < candidates.Length; i++) {
            if (candidates[i] > remain) break; // 剪枝
          
            current.Add(candidates[i]);
            Backtrack(candidates, remain - candidates[i], i); // 注意这里是i而不是i+1
            current.RemoveAt(current.Count - 1);
        }
    }
}

执行结果

  • 执行用时:104 ms
  • 内存消耗:42.8 MB

代码亮点

  1. 🎯 通过排序实现高效剪枝
  2. 💡 巧妙处理重复使用数字
  3. 🔍 优雅的回溯实现
  4. 🎨 代码结构清晰,易于理解

常见错误分析

  1. 🚫 没有对数组进行排序,导致剪枝失效
  2. 🚫 回溯时没有正确处理索引
  3. 🚫 重复组合的处理错误
  4. 🚫 剪枝条件判断不当

解法对比

解法时间复杂度空间复杂度优点缺点
暴力枚举O(n^target)O(target)实现简单效率极低
回溯+剪枝O(n^(target/min))O(target/min)效率较高需要排序
动态规划O(target * n)O(target)性能稳定不适用于此题

相关题目