组合总和- 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,4]和[4,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
相关推荐
xixixi777771 天前
Token 经济引爆 AI 产业加速:从百模大战到百虾大战,谁在定义 2026 的中国 AI?
大数据·人工智能·机器学习·ai·大模型·算力·通信
郝学胜-神的一滴1 天前
[简化版 GAMES 101] 计算机图形学 04:二维变换上
c++·算法·unity·godot·图形渲染·unreal engine·cesium
ZC跨境爬虫1 天前
海南大学交友平台开发实战day7(实现核心匹配算法+解决JSON请求报错问题)
前端·python·算法·html·json
xiaoyaohou111 天前
011、骨干网络改进(二):MobileNet、ShuffleNet等轻量骨干的适配
网络·深度学习·机器学习
计算机安禾1 天前
【数据结构与算法】第41篇:图论(五):拓扑排序与关键路径
c语言·数据结构·c++·算法·图论·visual studio
Q741_1471 天前
每日一题 力扣 1320. 二指输入的的最小距离 动态规划 C++ 题解
c++·算法·leetcode·动态规划
wfbcg1 天前
每日算法练习:LeetCode 76. 最小覆盖子串 ✅
算法·leetcode·职场和发展
Wect1 天前
LeetCode 149. 直线上最多的点数:题解深度剖析
前端·算法·typescript
qianpeng8971 天前
运动声源的到达结构仿真
算法
费曼学习法1 天前
线段树:区间查询的"终极武器",一文看透高效范围统计
算法