LeetCode 322 Coin Change (Python)

Posted by 小明MaxMing on March 11, 2021

题目

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

解题思路

dp[i]表示组成i所需的最少硬币数
dp[i] = min(dp[i], dp[i-coin] + 1) for c in coins if i >= coin
dp[0] = 0
dp[n]为所求

代码

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [float('inf')] * (amount + 1)
        dp[0] = 0
        for coin in coins:
            for i in range(coin, amount + 1):
                dp[i] = min(dp[i], dp[i - coin] + 1)
        return dp[amount] if dp[amount] != float('inf') else -1

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅