python-leetcode 47.组合总和
题目:
给一个无重复元素的整数数组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
源自力扣官方题解