[LeetCode]Coin Change@Python

Coin Change

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.

Example

Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Solution

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        MAX = float('inf')
        dp = [0] + [MAX]*amount
        for i in range(1, amount+1):
            dp[i] = min([dp[i-c] if i-c>=0 else MAX for c in coins]) + 1
        return dp[amount] if dp[amount]!=MAX else -1
上一篇:[数学基础]组合闲谈 - 2 - Stirling 数


下一篇:[HDU6304]Chiaki Sequence Revisited