39. Combination Sum
solution
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
path = []
# candidates.sort()
self.dfs(path, res, candidates, target, start=0)
return res
def dfs(self, path, res, candidates, target, start):
if target < 0: # 剪枝, 一定要有这步?
return
if target == 0:
res.append(path[:])
return
for i in range(start, len(candidates)):
path.append(candidates[i])
self.dfs(path, res, candidates, target - candidates[i], i) # 有放回i, 无放回i+1
path.pop()follow up
Last updated