给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1
。
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
输入: coins = [2], amount = 3
输出: -1
动态规划啦?:
# 设dp[i]为构成金额i的最优解,即凑成总金额所需的最少的硬币个数;
# 那么dp[1] = 1,dp[2] = 1,dp[5] = 1,因为coins中有此金额,直接拿来用即可;
# dp[i] = min(dp[i-1],dp[i-2],dp[i-5])+1。
小象学院ppt上的思路:
有[1],0和[2],1这两种情况当时没考虑。
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp=[-1]*(amount+1)
dp[0]=0
for i in range(1,amount+1):
for j in range(0,len(coins)):
if i>=coins[j] and dp[i-coins[j]]!=-1:
if dp[i]==-1 or dp[i]>dp[i-coins[j]]+1:
dp[i]=dp[i-coins[j]]+1
return dp[amount]
参考:将dp中的内容设置为无穷大——2<<31
class Solution(object):
def coinChange(self, coins, amount):
if amount == 0:
return 0
dp = list()
max_int = 2 << 31
for i in range(amount + 1):
if i not in coins:
dp.append(max_int)
else:
dp.append(1)
for i in range(amount + 1):
if i not in coins:
for j in coins:
if i - j > 0:
dp[i] = min(dp[i - j] + 1, dp[i])
return dp[amount] if dp[amount] != max_int else -1