Advertisement
bennyfromtheblock

39. Combination Sum

Mar 13th, 2024
902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. # We don't need a visited set if we traverse the solution in a way that creates no repeated visits to the same combination
  2. # ex. let candidates = [1, 2, 3, 4], target = 5
  3. # possible combinations: (1, 1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 3), ...
  4. # notice how there is no point visiting (1, 1, 2, 1) when we've already been at (1, 1, 1, 2)
  5. # In general, we don't need to look at previous candidates when finding 'neighbors'
  6. # So the problem structure is actually a tree (N-ary tree)
  7. # We can use a "start" index in the backtrack function to indicate the smallest index to search from
  8.  
  9. # TC: O(N^(T/M + 1)) where N is num candidates, T is target, M is min element in candidates.
  10. # Why? The height of the tree is T/M, since that's the longest combo we can form
  11. # maxmal number of nodes in N-ary tree is n^(h + 1)
  12.  
  13. # SC: T/M, max number of recursions stacks we incur and also max len of combo
  14.  
  15. class Solution:
  16.     def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
  17.         results = []
  18.  
  19.         def backtrack(remain, combo, start):
  20.             if not remain:
  21.                 results.append(combo.copy())
  22.                 return
  23.             elif remain < 0:
  24.                 return
  25.  
  26.             for i in range(start, len(candidates)):
  27.                 combo.append(candidates[i])
  28.                 backtrack(remain - candidates[i], combo, i)
  29.                 combo.pop()
  30.  
  31.         backtrack(target, [], 0)
  32.         return results
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement