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**_.
考虑到每一个解(如果有),都至少有一个数:
假如:
nums=[a,b,c]
target=x
则comb(x)=comb(x-a)+comb(x-b)+comb(x-c)
好像可以直接写代码了,递归式的。此处略去一些字。
那不递归怎么写呢?如果采用自底向上的方法
class Solution(object):
def combinationSum4(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
dp=[1]*(target+1)
for i in range(1,target+1):
res=0
for j in range(len(nums)):
if i>=nums[j]:
res+=dp[i-nums[j]]
dp[i]=res
return dp[-1]
第八行的dp[i]就是用来存取comb(target)的结果,我们只需要初始化第一个元素即 dp[0]=1;这里可以理解为:如果target=0,则nums中数的和为0的情况只有全0这一种。
11到13行,就是采用前文所诉的方法,自底部开始算dp.
代码可以通过,但是考虑是不完整的。
- 首先,如果target是小于零的,题目应直接返回0
if target<=0:return 0
- 其次,第8行的初始化也是有问题的,应该把dp初始化为除了首位,其它位置全部为0
dp = [1] + [0] * target
就其次的那点,并稍微优化:
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 j in nums:
if i>=j:
dp[i]+=dp[i-j]
return dp[-1]