322. 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 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.
Note:
leetcode 的 print 输出有大小限制
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [-1 for _ in range(amount+1)]
dp[0] = 0
c = [0 for _ in range(len(coins))]
for i in range(1,amount+1):
for j in range(len(coins)):
# print(coins)
temp = i - coins[j]
if temp < 0:
c[j] = float('inf')
else:
c[j] = dp[temp] + 1
if len(c) == 1:
dp[i] = c[0]
else:
dp[i] = min(*c)
# print(i,'--',dp)
# print(dp[-1],"www",dp[-1] == float('inf'))
if dp[-1] == float('inf'):
return -1
return dp[-1]
请多多指教。
文章标题:322. Coin Change
本文作者:顺强
发布时间:2019-08-18, 23:59:00
原始链接:http://shunqiang.ml/leetcode-322-coin-change/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。