Leetcode| 完全背包、518. 零钱兑换 II、377. 组合总和 Ⅳ Day44

完全背包

完全背包

def test_CompletePack():
    weight = [1, 3, 4]
    value = [15, 20, 30]
    bagWeight = 4
    dp = [0] * (bagWeight + 1)

    for i in range(len(weight)):
        for j in range(weight[i], bagWeight + 1):
            dp[j] = max(dp[j], dp[j - weight[i]] + value[i])

    print(dp[bagWeight])

test_CompletePack()

518. Coin Change II

dp[j]:凑成总金额j的货币组合数为dp[j]
dp[j] 就是所有的dp[j - coins[i]](考虑coins[i]的情况)相加。
所以递推公式:dp[j] += dp[j - coins[i]];

  • 如果求组合数就是外层for循环遍历物品,内层for遍历背包。
  • 如果求排列数就是外层for遍历背包,内层for循环遍历物品。
class Solution:
    def change(self, amount: int, coins: List[int]) -> 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]

377. Combination Sum IV

dp[i]: 凑成目标正整数为i的排列个数为dp[i]

  • 如果求组合数就是外层for循环遍历物品,内层for遍历背包。
  • 如果求排列数就是外层for遍历背包,内层for循环遍历物品。
class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:
        dp = [0] * (target + 1)
        dp[0] = 1

        for i in range(target + 1):         # 遍历背包
            for j in range(len(nums)):      # 遍历物品
                if i >= nums[j]:
                    dp[i] += dp[i - nums[j]]

        return dp[target]

你可能感兴趣的:(算法,leetcode,动态规划,算法)