给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1
。
示例 1:
输入: coins =[1, 2, 5]
, amount =11
输出:3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins =[2]
, amount =3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
思路:
动态规划。用dp[i] 表示组成 i 元所需要的最小硬币数。
显然对于coins数组里的所有元素j,所有的dp[j] = 1。
以样例输入一为例:
对于其他的dp[i] = 1 + min(dp[i - 1], dp[i - 2], dp[i - 5])
即求11元的答案可以转化为: 1个一元硬币 + 10元答案 或者 1个两元硬币 + 9元答案 或者1个五元硬币 + 6元答案。
所以dp[i] = 1 + min(dp[i - j]) for j in coins
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
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