LeetCode 第40题:组合总和 II

LeetCode 第40题:组合总和 II

题目描述

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次

注意: 解集不能包含重复的组合。

难度

中等

题目链接

点击在LeetCode中查看题目

示例

示例 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]
]

提示

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

解题思路

方法:回溯 + 剪枝

这是第39题的变体,主要区别在于:

  1. 每个数字只能使用一次
  2. 数组中可能包含重复数字
  3. 需要避免重复组合

关键点:

  1. 使用排序+剪枝避免重复组合
  2. 在同一层递归中跳过重复数字
  3. 每个数字只能使用一次

具体步骤:

  1. 对数组进行排序,方便剪枝和去重
  2. 使用回溯法搜索所有可能的组合:
    • 记录当前已选数字和
    • 同一层递归中跳过重复数字
    • 每个数字只能使用一次
  3. 返回所有有效组合

时间复杂度:O(2^n)
空间复杂度:O(n),递归栈的深度

图解思路

回溯树分析表

层级 当前和 可选数字 选择 是否跳过
0 0 [1,1,2,5,6,7,10] 1
1 1 [1,2,5,6,7,10] 1
2 2 [2,5,6,7,10] 6
回溯 1 [2,5,6,7,10] 2
回溯 1 [5,6,7,10] 5

剪枝策略示意图

当前数字 下一个数字 是否跳过 原因
1 1 同层重复
2 2 同层重复
5 6 不同数字
6 7 不同数字

代码实现

public class Solution {
    private IList<IList<int>> result = new List<IList<int>>();
    private List<int> current = new List<int>();
  
    public IList<IList<int>> CombinationSum2(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;
          
            // 跳过同一层的重复数字
            if (i > start && candidates[i] == candidates[i-1]) continue;
          
            current.Add(candidates[i]);
            Backtrack(candidates, remain - candidates[i], i + 1); // 注意这里是i+1
            current.RemoveAt(current.Count - 1);
        }
    }
}

执行结果

  • 执行用时:92 ms
  • 内存消耗:42.5 MB

代码亮点

  1. 🎯 高效的重复组合处理
  2. 💡 巧妙的剪枝策略
  3. 🔍 优雅的回溯实现
  4. 🎨 代码结构清晰,易于理解

常见错误分析

  1. 🚫 没有正确处理重复数字
  2. 🚫 剪枝条件不完整
  3. 🚫 递归参数传递错误
  4. 🚫 结果集去重逻辑错误

解法对比

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

相关题目

posted @   旧厂街小江  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示