-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0039-combination-sum.py
50 lines (45 loc) · 1.53 KB
/
0039-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
# time complexity: O(n^(t/m) + 1)
# space complexity: O(t/m)
from typing import List
# Backtrack
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
def backtrack(start: int, comb: List[int], remain: int):
if remain == 0:
result.append(list(comb))
return
elif remain < 0:
return
else:
for i in range(start, len(candidates)):
comb.append(candidates[i])
backtrack(i, comb, remain - candidates[i])
comb.pop()
backtrack(0, [], target)
return result
# time complexity: O(t*n*s^2log(s))
# space complexity: O(t*n*c)
# Bottom Up
class Solution:
def combinationSum(self, nums: List[int], target: int) -> List[List[int]]:
dp = [[] for _ in range(target + 1)]
dp[0].append([])
for i in range(1, target + 1):
for j in range(len(nums)):
if nums[j] <= i:
for prev in dp[i - nums[j]]:
temp = prev + [nums[j]]
temp.sort()
if temp not in dp[i]:
dp[i].append(temp)
return dp[target]
candidates = [2, 3, 6, 7]
target = 7
print(Solution().combinationSum(candidates, target))
candidates = [2, 3, 5]
target = 8
print(Solution().combinationSum(candidates, target))
candidates = [2]
target = 1
print(Solution().combinationSum(candidates, target))