注意这里的for循环里面是dfs(i)。我们可以把解空间想象成一幅树,对于candidates=[2,3,6,7]
target=7,可以想象第一行有2 3 6 7,第二行的第一个为2 3 6 7,第二个是 3 6 7,第三个是6 7,第四个为 7,依次进行下去,所以是dfs(i),
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans=[]
n=len(candidates)
def dfs(index,ant,num):
if ant==target:
ans.append(list(num))
return
if index==n:
return
for i in range(index,n):
if ant+candidates[i]>target:
continue
num.append(candidates[i])
dfs(i,ant+candidates[i],num)
num.pop(-1)
dfs(0,0,[])
return ans
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans=[]
n=len(candidates)
def dfs(index,ant,num):
if ant>target:
return
if ant==target:
ans.append(list(num))
return
if index==n:
return
num.append(candidates[index])
dfs(index,ant+candidates[index],num)
num.pop(-1)
dfs(index+1,ant,num)
dfs(0,0,[])
return ans