思路动态规划
对于给定的一个目标,我们自顶向下遍历所有可能
最后在所有可能里选择最小的那个
自底向上法:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [0x3f3f3f3f]*(amount+1)
dp[0] = 0 #base case
for coin in coins:
for i in range(coin,amount+1):
dp[i] = min(dp[i],dp[i-coin] + 1)
return dp[amount] if dp[amount] != 0x3f3f3f3f else -1
自顶向下法:
由于可能存在很多的重复计算,可以用一个count数组作为备忘录
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
count = [0]*amount
def dp(coins,amount):
if amount == 0:
return 0
if amount < 0:
return -1
if count[amount-1] != 0:
return count[amount-1]
min1 = 0x3f3f3f3f
for coin in coins:
res = dp(coins,amount-coin)
if res >= 0 and res < min1:
min1 = res + 1
count[amount-1] = min1 if min1 != 0x3f3f3f3f else -1
return count[amount-1]
return dp(coins,amount)