代码随想录day44

题目:零钱兑换2
题解:

1)对于完全背包问题,同一件物品拿取的次数可以是无数次
2)先遍历物品,然后是背包。在遍历背包的时候,正序遍历的时候,每个物品可以放多次,但是倒叙遍历,每个物品只能放一次。
3)对于完全背包,先遍历物品还是背包都是ok的
4)所以递推公式:dp[j] += dp[j - coins[i]];
这个递推公式大家应该不陌生了,在讲解01背包题目的时候在这篇494. 目标和 (opens new window)中就讲解了,求装满背包有几种方法,公式都是:dp[j] += dp[j - nums[i]];

代码:
class Solution(object):
    def change(self, amount, coins):
        """
        :type amount: int
        :type coins: List[int]
        :rtype: int
        """
        dp = [0] *(amount + 1)
        dp[0] = 1
        for i in range(len(coins)):
            for j in range(coins[i], amount + 1):
                dp[j] += dp[j - coins[i]]
        return dp[amount]
题目:组合总和2
题解:

1)先遍历背包,再遍历物品,求的是排列数;先遍历物品,再遍历背包,求的是组合数

代码:
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 n in nums:
                if i >= n:
                    dp[i] += dp[i - n]#迭代函数要注意
        return dp[target]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值