-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcombination_sum.py
38 lines (27 loc) · 919 Bytes
/
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. Combination Sum
# https://leetcode.com/problems/combination-sum/
from typing import List
from copy import copy
class Solution:
def dfs(self, target, candidates, result, candi):
if target == 0:
return True
elif target < 0:
return False
for num in candidates:
if candi and candi[-1] > num:
continue
r = copy(candi)
r.append(num)
if self.dfs(target - num, candidates, result, r):
result.append(r)
return False
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates = sorted(candidates)
result = []
self.dfs(target, candidates, result, [])
return result
if __name__ == '__main__':
sol = Solution()
print(sol.combinationSum([2, 3, 6, 7], 7))
print(sol.combinationSum([2, 3, 5], 8))