-
Notifications
You must be signed in to change notification settings - Fork 24
/
39 - Combination Sum.py
52 lines (48 loc) · 1.68 KB
/
39 - 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
40
41
42
43
44
45
46
47
48
49
50
51
# Solution 1: Recursively calculate solution, hash to avoid duplicate solutions
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.solutions = set()
self.candidates = candidates
self.checkSolution(target, [])
ans = []
for solution in self.solutions:
ans.append(list(solution))
return ans
def checkSolution(self, target, solution):
if target <= 0:
if target == 0:
solution.sort()
self.solutions.add(tuple(solution))
return
for candidate in self.candidates:
newSolution = solution[:]
newSolution.append(candidate)
self.checkSolution(target - candidate, newSolution)
# Solution 2: Avoid generating duplicate solutions at all by keeping track of index
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
self.checked = set()
self.solutions = []
self.candidates = candidates
self.checkSolution(target, [], 0)
return self.solutions
def checkSolution(self, target, solution, i):
if target <= 0:
if target == 0:
self.solutions.append(solution)
return
while i < len(self.candidates):
newSolution = solution[:]
newSolution.append(self.candidates[i])
self.checkSolution(target - self.candidates[i], newSolution, i)
i += 1