1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution: def __init__(self): self.sum = 0 self.path,self.result = [],[] def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: candidates.sort() def combinationSum_(candidates,target,sum,startindex) -> List[List[int]]: if self.sum > target: return if self.sum == target: self.result.append(self.path.copy()) return for i in range(startindex,len(candidates)): if self.sum + candidates[i]>target: break self.path.append(candidates[i]) self.sum += candidates[i] combinationSum_(candidates,target,self.sum,i) reduce = self.path.pop() self.sum -= reduce return self.result return combinationSum_(candidates,target,self.sum,0)
|