python-leetcode 57.组合总和

题目:

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

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

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


方法一:递归回溯

class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()#排序,减少无效递归
        ans=[] #存储所有满足条件的组合
        path=[] #存储当前正在尝试的组合
        def dfs(i,left): #当前遍历到 candidates 的索引,left目前需要的目标和
            if left==0: #找到了一组合法的组合
                ans.append(list(path))  #存储 path 的副本,否则 path 继续变化
                return 
            if i ==len(candidates) or left<candidates[i]:#索引超出范围,如果 left 已经小于当前候选数,后续的数(更大)也不可能满足 left,直接返回
                return 
            dfs(i+1,left)#跳过当前元素i,直接递归处理下一个元素
            path.append(candidates[i])#将当前元素加入 
            dfs(i,left-candidates[i])
            path.pop()#移除 path 中最后添加的元素,以尝试其他组合
        dfs(0,target)
        return ans
        return ans

源自力扣官方题解
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值