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.
答案非常简洁,值得深入去理解动态规划的东西
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp = [0 for _ in xrange(target+1)]
dp[0] = 1
for i in xrange(1, len(dp)):
for j in xrange(len(nums)):
if i - nums[j] >= 0:
dp[i] += dp[i - nums[j]]
return dp[target]
递归版本的答案
def combination(self, nums, target):
if target == 0:
return 1
result = 0
for v in nums:
if target - v >= 0:
result += self.combination(nums, target - v)
return result