Last active
May 15, 2021 11:42
-
-
Save fpaupier/224264003d149de076abef7854b99083 to your computer and use it in GitHub Desktop.
39. Combination Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: | |
solutions: List[List[int]] = [] | |
n: int = len(candidates) | |
candidates.sort() # Helps us to prune the search space (cf line 15) | |
def backtrack(sum_: int, start_idx: int, cur_list: List[int]) -> None: | |
if sum_ == target: # Goal - base case | |
solutions.append(cur_list) | |
return | |
for i in range(start_idx, n): | |
if sum_ + candidates[i] <= target: | |
backtrack(sum_ + candidates[i], i, cur_list + [candidates[i]]) # Explore further the solution space | |
else: | |
return # Pruning - no need to explore further if the sum is above the target value. | |
backtrack(0, 0, []) | |
return solutions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment