-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path377.py
More file actions
100 lines (81 loc) · 2.24 KB
/
377.py
File metadata and controls
100 lines (81 loc) · 2.24 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
'''
377. Combination Sum IV
Given an integer array with all positive numbers and no duplicates, find
the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
'''
class Solution(object):
def combinationSum4_BottomUp(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0 for _ in range(target + 1)]
dp[0] = 1
for i in range(1, target + 1):
for j in range(len(nums)):
if i >= nums[j]:
dp[i] += dp[i - nums[j]]
return dp[-1]
def combinationSum4_TopDown(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [-1 for _ in range(target + 1)]
dp[0] = 1
return self.help(nums, target, dp)
def help(self, nums, target, dp):
print("+++++++++++++++++++++++++++++")
print(dp)
print(target)
if dp[target] != -1:
return dp[target]
count = 0
for i in range(len(nums)):
if target >= nums[i]:
count += self.help(nums, target - nums[i], dp)
dp[target] = count
return count
# naive recursion
def combinationSum4_slow(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# TLE when nums = [4, 2, 1], target = 32
if target == 0:
return 1
count = 0
for num in nums:
if target >= num:
count += self.combinationSum4(nums, target - num)
return count
def test():
# nums = [4, 2, 1]
# target = 32
nums = [1, 2]
target = 5
sol = Solution()
print(sol.combinationSum4_TopDown(nums, target))
if __name__ == "__main__":
test()