322. Coin Change
Description:
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 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
解题思路:
Python已经AC的代码:
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [amount + 1 for _ in range(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 -1 if dp[amount] >= amount + 1 else dp[amount]
Reference:
【1】花花酱 LeetCode 322. Coin Change - 刷题找工作 EP148,地址:https://www.bilibili.com/video/av31621107?from=search&seid=12222304351393275021
Microstrong0305 博客专家 发布了285 篇原创文章 · 获赞 892 · 访问量 111万+ 关注