-
Notifications
You must be signed in to change notification settings - Fork 0
/
39-Combination_Sum.py
40 lines (27 loc) · 1.1 KB
/
39-Combination_Sum.py
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
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def dfs( need, curr, start ):
if need == 0:
result.append( list(curr) )
return
for idx, c in enumerate(candidates[start:]):
if need >= c:
dfs( need-c, curr + [c], start+idx )
dfs( target, [], 0 )
return result
class Solution_backtrack:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def backtr( need, curr, start ):
if need == 0:
result.append( list(curr) )
return
elif need < 0:
return
for idx, c in enumerate(candidates[start:]):
curr.append(c)
backtr( need-c, curr, start+idx )
curr.pop()
backtr( target, [], 0 )
return result