-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00039-combination_sum.py
More file actions
40 lines (27 loc) · 883 Bytes
/
00039-combination_sum.py
File metadata and controls
40 lines (27 loc) · 883 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
38
39
40
# 39: Combination Sum
# https://leetcode.com/problems/combination-sum/
from typing import List
class Solution:
# SOLUTION
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
current = []
def backtrack(target: int, start: int) -> None:
if start >= len(candidates) or target < 0 : return
if target == 0:
result.append(current.copy())
return
current.append(candidates[start])
backtrack(target - candidates[start], start)
current.pop()
backtrack(target, start + 1)
backtrack(target, 0)
return result
if __name__ == "__main__":
o = Solution()
# INPUT
candidates = [2,3,6,7]
target = 7
# OUTPUT
result = o.combinationSum(candidates, target)
print(result)