-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcombinationSum.py
34 lines (26 loc) · 1.01 KB
/
combinationSum.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
class Solution:
def combinationSum(self, cand, target):
rtn = []
def backtracking(cand, target, tmp:List[int]):
if target == 0:
rtn.append(tmp)
if target < 0:
return
for i in range(len(cand)):
# cand[i:] factorial comb trick
backtracking(cand[i:], target-cand[i], tmp + [cand[i]])
backtracking(cand, target, [])
return rtn
class Solution:
def combinationSum(self, cand: List[int], target: int) -> List[List[int]]:
rtn = []
def dfs(path:List[int], remain:int, tmp:List[int]):
if remain < 0:
return
if remain == 0:
rtn.append(tmp)
return
for i in range(0, len(path)):
dfs(path[i:], remain-path[i], tmp + [path[i]])
dfs(cand, target, [])
return rtn