smj007

Combination Sum

Aug 24th, 2025
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.75 KB | None | 0 0
  1. class Solution:
  2.     def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
  3.        
  4.         def backtrack(remain: int, combs: List[int], index: int) -> None:
  5.  
  6.             if remain == 0:
  7.                 # this ensures that each solution stored in results
  8.                 # is independent of future modifications to combs.
  9.                 results.append(list(combs))
  10.  
  11.             if remain < 0:
  12.                 return
  13.  
  14.             # recursive: append the number
  15.             for i in range(index, len(candidates)):
  16.                 combs.append(candidates[i])
  17.                 backtrack(remain - candidates[i], combs, i)
  18.                 combs.pop()
  19.  
  20.         results = []
  21.         backtrack(target, [], 0)
  22.         return results
  23.  
Advertisement
Add Comment
Please, Sign In to add comment