Python小练习系列 Vol.8:组合总和(回溯 + 剪枝 + 去重)

🧠 Python小练习系列 Vol.8:组合总和(回溯 + 剪枝 + 去重)

💡 本期我们挑战 LeetCode 回溯题三件套之一 ------ 组合总和,深入掌握路径构建、剪枝策略与去重技巧!


🧩 一、题目描述

给定一个无重复正整数数组 candidates 和一个目标值 target,找出所有和为 target 的组合。每个数可以重复使用无限次。

示例:

python 复制代码
输入: candidates = [2,3,6,7], target = 7
输出: [[2,2,3], [7]]

🧠 二、解题思路

我们采用回溯算法 + 剪枝

  1. 尝试将 candidates[i] 加入当前组合路径;
  2. 若路径之和超过 target,立即剪枝;
  3. 每次递归从当前下标开始,允许重复使用数字;
  4. 当路径之和正好等于 target,加入结果集。

👨‍💻 三、Python代码实现

python 复制代码
def combination_sum(candidates, target):
    res = []
    path = []

    def dfs(start, total):
        if total == target:
            res.append(path[:])
            return
        if total > target:
            return
        for i in range(start, len(candidates)):
            path.append(candidates[i])
            dfs(i, total + candidates[i])  # 允许重复取,索引不变
            path.pop()

    dfs(0, 0)
    return res

📌 四、运行示例

python 复制代码
print(combination_sum([2, 3, 6, 7], 7))
# 输出:[[2, 2, 3], [7]]

🧩 五、解题小结

步骤 说明
递归结构 当前索引 + 当前路径和
剪枝条件 如果 total > target,立即 return
去重策略 控制递归起点,避免重复排列组合

✅ 本题是"回溯选数"类题目的标准模板。


💡 六、进阶挑战

  • 📦 如果数组中可能有重复数字,如何避免结果重复?(组合总和 II)
  • 🧠 只能使用每个数字一次,怎么改动递归逻辑?
  • 🚀 如果要求找出总和为 target 的最短组合呢?

❤️ 结语

组合总和不仅考验回溯技巧,更是刷题进阶路上的重要关卡,搞懂它,下一题你会更轻松!


👉 点个赞 👍 + 收藏 🌟,我们下期再战算法高地!

相关推荐
张人玉12 分钟前
C# 常量与变量
java·算法·c#
dme.14 分钟前
Javascript之DOM操作
开发语言·javascript·爬虫·python·ecmascript
加油吧zkf24 分钟前
AI大模型如何重塑软件开发流程?——结合目标检测的深度实践与代码示例
开发语言·图像处理·人工智能·python·yolo
t_hj25 分钟前
python规划
python
czhc114007566341 分钟前
Linux 76 rsync
linux·运维·python
weixin_446122461 小时前
LinkedList剖析
算法
悠悠小茉莉1 小时前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
m0_625686551 小时前
day53
python
Real_man2 小时前
告别 requirements.txt,拥抱 pyproject.toml和uv的现代Python工作流
python
百年孤独_2 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表