-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination_sum.py
More file actions
37 lines (27 loc) · 907 Bytes
/
combination_sum.py
File metadata and controls
37 lines (27 loc) · 907 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution:
def combinationSum(self, candidates, target):
if not candidates:
return []
result = []
def backtrack(solution, idx, curr_sum):
if curr_sum == target:
result.append(solution[:])
return
if idx == len(candidates) or curr_sum > target:
return
# choose
solution.append(candidates[idx])
backtrack(solution, idx, curr_sum + candidates[idx])
solution.pop()
# don't choose
backtrack(solution, idx + 1, curr_sum)
backtrack([], 0, 0)
return result
if __name__ == "__main__":
solution = Solution()
candidates = [2, 3, 6, 7]
target = 7
result = solution.combinationSum(candidates, target)
assert result == [[2, 2, 3], [7]]
print(result)
print("Test Case 1 Passed!")