代码随想录算法训练营第四十四天| 377. 组合总和 Ⅳ,518. 零钱兑换 II

代码随想录算法训练营第四十四天

  • 377. 组合总和 Ⅳ
  • 518. 零钱兑换 II

377. 组合总和 Ⅳ

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.12
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/combination-sum-iv/
from typing import List


class Solution:
    """
    dp[j] 表示amount为j的组合数
    递推公式:dp[j] += dp[j-1] + dp[j-2] + dp[j-5]
    边界条件dp[0] = 1
    """

    def combinationSum4(self, nums: List[int], target: int) -> int:
        dp = [0] * (target + 1)
        dp[0] = 1

        for j in range(0, target + 1):
            for i in range(len(nums)):
                if j >= nums[i]:
                    dp[j] += dp[j - nums[i]]
        return dp[target]


if __name__ == '__main__':
    nums = [1, 2, 3]
    target = 4
    s = Solution()
    print(s.combinationSum4(nums, target))

518. 零钱兑换 II

代码

#  !/usr/bin/env  python
#  -*- coding:utf-8 -*-
# @Time   :  2022.12
# @Author :  hello algorithm!
# @Note   :  https://leetcode.cn/problems/coin-change-ii/
from typing import List


class Solution:
    """
    dp[j] 表示amount为j的组合数
    递推公式:dp[j] += dp[j-1] + dp[j-2] + dp[j-5]
    边界条件dp[0] = 1
    """

    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]


if __name__ == '__main__':
    amount = 3
    coins = [2]
    s = Solution()
    print(s.change(amount, coins))

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