组合总和- python-回溯哦&剪枝

题目:

思路:

K神的思路清晰明了,推荐阅读:

https://leetcode.cn/problems/combination-sum/solutions/2363929/39-zu-he-zong-he-hui-su-qing-xi-tu-jie-b-9zx7/?envType=study-plan-v2&envId=top-100-likedhttps://leetcode.cn/problems/combination-sum/solutions/2363929/39-zu-he-zong-he-hui-su-qing-xi-tu-jie-b-9zx7/?envType=study-plan-v2&envId=top-100-liked跟全排列的做法差不多,但是需要两次剪枝:一是和不能超过目标值;二是去重3,44,3是一样的

代码:

复制代码
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        def backtrack(
            state: list[int], target: int, choices: list[int], start: int, res: list[list[int]]
        ):
            if target == 0:
                res.append(list(state))
                return
            for i in range(start,len(choices)):#从start开始,能去重
                if target - choices[i] < 0:#结果不能大于target
                    break
                state.append(choices[i])
                backtrack(state,target-choices[i],choices,i,res)#因为可以重复选,所以这里的start是i而不是i+1
                state.pop()
        
        state = []
        candidates.sort()#在遍历所有选择时,当子集和超过 target 时直接结束循环,因为后边的元素更大,其子集和都一定会超过 target 。
        start = 0
        res = []
        backtrack(state,target,candidates,start,res)
        return res
相关推荐
旋生万物14 分钟前
电磁力 = 螺旋联络的 90° 旋转?麦克斯韦方程组的几何重构
人工智能·python·算法·机器学习·copilot·世界模型·物理ai
余俊晖38 分钟前
多模态大模型细粒度视觉理解:Vision-OPD在线策略自蒸馏技术方案概述
人工智能·深度学习·算法·多模态·opd
脚踏实地皮皮晨1 小时前
003003001_Grid控件
开发语言·windows·算法·c#·visual studio
Hi李耶1 小时前
【LeetCode】6-Z字形变换
算法·leetcode·职场和发展
XiaoYu1__1 小时前
算法进阶·其一:用SCC、Tarjan算法与缩点思想解决有向图的连通关系及2-SAT问题的拓展
算法
小O的算法实验室1 小时前
AAAI-26,全局相关性学习:通过谱图神经网络增强进化算法
神经网络·学习·算法
段一凡-华北理工大学1 小时前
AI推动工业智能化转型~系列文章07:分类与诊断算法体系:故障识别的完整工具箱
数据库·人工智能·算法·机器学习·分类·数据挖掘·高炉炼铁智能化
简信CRM1 小时前
适合离散制造中小工厂 MES 系统推荐
算法·机器学习·制造
AKA__Zas1 小时前
芝士算法(前缀和2.0)
java·数据结构·算法·leetcode·哈希算法·学习方法
皓月斯语2 小时前
B3867 [GESP202309 三级] 小杨的储蓄 题解
c++·算法·题解