-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path052-combination-sum.py
More file actions
54 lines (38 loc) · 1.63 KB
/
052-combination-sum.py
File metadata and controls
54 lines (38 loc) · 1.63 KB
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
50
51
52
53
54
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(candidates: List[int], candidate_index: int, selected_candidates: List[int], target: int):
if target < 0:
return
if target == 0:
res.append(selected_candidates)
return
for i in range(candidate_index, len(candidates)):
t = target - candidates[i]
backtrack(candidates, i, selected_candidates +
[candidates[i]], t)
res = []
if not candidates:
return res
backtrack(candidates, 0, [], target)
return res
def combinationSumv1(self, candidates: List[int], target: int) -> List[List[int]]:
def backtrack(candidates: List[int], candidate_index: int, selected_candidates: List[int], target: int):
if target < 0:
return
if target == 0:
res.append(selected_candidates)
return
if candidate_index >= len(candidates):
return
multiplier = target // candidates[candidate_index]
for i in range(0, multiplier+1):
t = target - i * candidates[candidate_index]
backtrack(candidates, candidate_index + 1,
selected_candidates + ([candidates[candidate_index]] * i), t)
res = []
if not candidates:
return res
backtrack(candidates, 0, [], target)
return res
print(Solution().combinationSum([2, 3, 4], 9))