题目的描述
解题思路
这道题看起来更像是树的深度遍历的一种变体,只不过是现在的树允许有重复的值,其实只需要通过for循环就可以解决这种变体的题目。大家可能之前做过路径搜索的问题,类似路径搜索。
解题代码
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(candidates,begin,size,path,res,target):
if target==0:
res.append(path)
return
for index in range(begin,size):
residue = target-candidates[index]
if residue<0:
break
dfs(candidates,index,size,path+[candidates[index]],res,residue)
size=len(candidates)
if size==0:
return []
candidates.sort()
path=[]
res=[]
dfs(candidates,0,size,path,res,target)
return res