-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
49 lines (37 loc) · 1.12 KB
/
Solution.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
41
42
43
44
45
46
47
48
49
# 1, O(n) = k * C(n, k)
def dfs(candidates, start, elements, target, res):
if target < 0:
return
if target == 0:
# print(list(elements))
res.append(list(elements))
return
for i in range(start, len(candidates)):
num = candidates[i]
elements.append(num)
dfs(candidates, i, elements, target - num, res)
elements.pop()
def combinationSumRecursion(candidates, target):
res = []
dfs(candidates, start=0, elements=[], target, res)
return res
# 2
def combinationSumIteration(candidates, target):
res = []
stack = [([], 0, target)]
while stack:
elements, start, target = stack.pop()
# base case
if target == 0:
print(list(elements))
res.append(list(elements))
continue
# dfs
for i in range(start, len(candidates)):
num = candidates[i]
if target - num < 0:
continue
# elements.append(num)
stack.append((elements + [num], i, target - num))
# elements.pop()
return res