377. 组合总和 Ⅳ(动态规划)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_33598125/article/details/100823356

给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。

示例:

nums = [1, 2, 3]
target = 4

所有可能的组合为:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

请注意,顺序不同的序列被视作不同的组合。

因此输出为 7。

进阶:
如果给定的数组中含有负数会怎么样?
问题会产生什么变化?
我们需要在题目中添加什么限制来允许负数的出现?

【中等】
【分析】动态规划。
定义dp[i]为金额为i时的组合总数。

  • d p [ 0 ] = 1 dp[0]=1
  • d p [ i ] = c o i n d p [ i c o i n ] , c o i n c o i n s dp[i]=\sum_{coin}dp[i-coin],coin\in coins
class Solution(object):
    def combinationSum4(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(target+1):
            for num in nums:
                if i-num>=0:
                    dp[i]+=dp[i-num]
        return dp[-1]

一开始首先想到回溯法,但是这种方法就是一旦回溯的次数太多就容易超时。所以只做参考。

class Solution(object):
    def combinationSum4(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        res=0
        return dfs(nums,target,res)
        
    def dfs(self,nums,target,res):
        if target==0:
            res+=1
            return res
        for i in nums:
            if target-i>=0:
                res=self.dfs(nums,target-i,res)
        return res 

猜你喜欢

转载自blog.csdn.net/qq_33598125/article/details/100823356
今日推荐