📅  最后修改于: 2022-03-11 14:55:27.026000             🧑  作者: Mango
Recursion:
def minimumNumberOfCoins(coins,numberOfCoins,value):
def recur(coins, n, value):
if n == 0:
return float("inf")
if value == 0:
return 0
if coins[n-1] > value:
return recur(coins, n-1, value)
else:
return min(1 + recur(coins, n, value-coins[n-1]), recur(coins, n-1, value))
res = recur(coins,numberOfCoins,value)
if res == float("inf"):
return 0
return res
Bottom Up:
def coinChange(coins, amount):
n = len(coins)
def recur(amount,coins,n,dp):
if dp[n][amount] != -1:
return dp[n][amount]
if coins[n-1] > amount:
dp[n][amount] = recur(amount,coins,n-1,dp)
if coins[n-1] <= amount:
dp[n][amount] = min(1 + recur(amount - coins[n-1],coins,n,dp), recur(amount,coins,n-1,dp))
return dp[n][amount]
dp = [[-1 for i in range(amount+1)] for j in range(n+1)]
for i in range(amount+1):
dp[0][i] = float("inf")
for i in range(1, n+1):
dp[i][0] = 0
recur(amount,coins,n,dp)
if dp[n][amount] == float("inf"):
return -1
return dp[n][amount]
Top Down:
def coinChange(coins, amount):
n = len(coins)
def recur(amount,coins,n,dp):
for i in range(1, n+1):
for j in range(1, amount+1):
if coins[i-1] > j:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = min(1 + dp[i][j-coins[i-1]], dp[i-1][j])
dp = [[-1 for i in range(amount+1)] for j in range(n+1)]
for i in range(1, amount+1):
dp[0][i] = float("inf")
for i in range(n+1):
dp[i][0] = 0
recur(amount,coins,n,dp)
if dp[n][amount] == float("inf"):
return -1
return dp[n][amount]