-
Notifications
You must be signed in to change notification settings - Fork 44
/
combination-sum-iv.py
111 lines (105 loc) · 2.85 KB
/
combination-sum-iv.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
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
101
102
103
104
105
106
107
108
109
110
111
# VO
# IDEA : DP
# dp[x+y] = dp[x+y] + dp[x] (for all x in range(target + 1), for all y in nums)
# -> dp[x] : # of ways can make sum = x from sub-nums
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for x in range(target + 1):
for y in nums:
if x + y <= target:
dp[x + y] += dp[x]
return dp[target]
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79343825
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for i in range(1, target + 1):
for num in nums:
if i >= num:
dp[i] += dp[i - num]
return dp.pop()
# V1'
# IDEA : DP
# http://bookshadow.com/weblog/2016/07/25/leetcode-combination-sum-iv/
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target + 1)
dp[0] = 1
for x in range(target + 1):
for y in nums:
if x + y <= target:
dp[x + y] += dp[x]
return dp[target]
# V1''
# https://www.hrwhisper.me/leetcode-combination-sum-iv/
# IDEA DP
# dp[i] += dp[i-num]
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [1] + [0] * target
for i in xrange(1, target + 1):
for x in nums:
if i >= x:
dp[i] += dp[i - x]
return dp[target]
# V1''
# https://www.hrwhisper.me/leetcode-combination-sum-iv/
# IDEA : DP
# dp[i+num] += dp[i]
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [1] + [0] * target
for i in xrange(target + 1):
for x in nums:
if i + x <= target:
dp[i + x] += dp[i]
return dp[target]
# V2
# Time: O(nlon + n * t), t is the value of target.
# Space: O(t)
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0] * (target+1)
dp[0] = 1
nums.sort()
for i in range(1, target+1):
for j in range(len(nums)):
if nums[j] <= i:
dp[i] += dp[i - nums[j]]
else:
break
return dp[target]