-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsum2.py
More file actions
38 lines (33 loc) · 1.12 KB
/
sum2.py
File metadata and controls
38 lines (33 loc) · 1.12 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
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
"""
# Bruteforce
import itertools
result = set()
maxi = target//min(candidates)
#print(maxi)
for i in range(1, maxi+1):
for comb in itertools.product(candidates, repeat=i):
if sum(comb) == target:
comb = tuple(sorted(comb))
result.add(comb)
return list(result)
"""
def backtrack(result, temp, candidates, remain, start):
if remain < 0:
return
elif remain == 0:
result.append(temp)
return
else:
for i in range(start, len(candidates)):
backtrack(result, temp+[candidates[i]], candidates, remain-candidates[i], i)
candidates = sorted(candidates)
result = []
backtrack(result, [], candidates, target, 0)
return result