xxxxxxxxxx
class Solution
{
//Function to find the minimum number of coins to make the change
//for value using the coins of given denominations.
public long minimumNumberOfCoins(int coins[],int n,int value)
{
//long res=method1(coins,0,n,value,0);
//return res==Integer.MAX_VALUE?-1:res;
return method2(coins,n,value);
}
long method1(int coins[],int i,int n,int val,int no){
if(val<0) return Integer.MAX_VALUE;
if(val==0) return no;
if(i==n){
return Integer.MAX_VALUE;
}
return Math.min(method1(coins,i+1,n,val,no),method1(coins,i,n,val-coins[i],no+1));
}
long method2(int coins[],int n,int value){
long dp[]=new long[value+1];
for(int i=1;i<=value;++i){
dp[i]=Integer.MAX_VALUE;
for(int j=0;j<n;++j) if(i-coins[j]>=0) dp[i]=Math.min(dp[i],dp[i-coins[j]]+1);
}
long res=dp[value];
return res==Integer.MAX_VALUE?-1:res;
}
long method3(int coins[],int n,int value){
int dp[]=new int[value+1];
dp[0]=0;
for(int i=1;i<=value;i++) dp[i]=Integer.MAX_VALUE;
for(int i=1;i<=value;i++){
for(int j=0;j<n;j++){
if(coins[j]<=i){
int sub_res=dp[i-coins[j]];
if(sub_res!=Integer.MAX_VALUE){
dp[i]=Math.min(dp[i],sub_res+1);
}
}
}
}
if(dp[value]==Integer.MAX_VALUE) return -1;
return (long)dp[value];
}
}
xxxxxxxxxx
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]