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**_.

考虑到每一个解(如果有),都至少有一个数:
假如:
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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值