思路
当amount in coins,说明当前交换的最少硬币为1
如果amount-coins ==-1 说明当前的换硬币方式不能组成总金额
如果amount-coins !=-1 说明当前的换硬币方式能组成总金额。找到可以换硬币的所有方式,找出换硬币最少
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if amount == 0:
return 0
coins.sort()
minp = coins[0]
if amount<minp:
return -1
if amount in coins:
return 1
if len(coins)==1 and amount%coins[0]==0:
return amount//coins[0]
dp = [-1]*(amount+1)
dp[minp]=1
for i in range(minp+1,amount+1):
t = pow(10,4)
for j in coins:
if i-j<0:
break
if i-j==0:
t = 1
break
else:
if dp[i-j]== -1:
continue
else:
t = min(t,dp[i-j]+1)
if t != pow(10,4):
dp[i]=t
return dp[amount]