combination-sumV2.py (724B)
1 class Solution: 2 def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 3 candidates.sort() 4 return combine(candidates, target, [], 0) 5 6 7 def combine(candidates, target, current, left_ptr): 8 9 if target == 0: 10 return [current] 11 12 current_index = left_ptr 13 results = [] 14 15 while current_index < len(candidates) and candidates[current_index] <= target: 16 17 cp_ls = current.copy() 18 cp_ls.append(candidates[current_index]) 19 with_current = combine( 20 candidates, target - candidates[current_index], cp_ls, current_index 21 ) 22 current_index += 1 23 24 for ans in with_current: 25 results.append(ans) 26 27 return results