-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path01_combination_sum.py
39 lines (29 loc) · 914 Bytes
/
01_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
class Solution:
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
res = []
def dfs(i, cur, total):
if total == target:
res.append(cur.copy())
return
if i >= len(candidates) or total > target:
return
cur.append(candidates[i])
dfs(i, cur, total + candidates[i])
cur.pop()
dfs(i + 1, cur, total)
dfs(0, [], 0)
return res
if __name__ == "__main__":
obj = Solution()
candidates1 = [2,3,6,7]
target1 = 7
res1 = obj.combinationSum(candidates1, target1)
print(res1)
candidates2 = [2,3,5]
target2 = 8
res2 = obj.combinationSum(candidates2, target2)
print(res2)
candidates3 = [2]
target3 = 1
res3 = obj.combinationSum(candidates3, target3)
print(res3)