322. Coin Change
322. Coin Change
Medium
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return
-1.
Example 1:
Input: coins =[1, 2, 5], amount =11Output:3Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins =[2], amount =3Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
You may assume that you have an infinite number of each kind of coin.
Idea:
two arguments coins and amount. change this function to dp. only to initial one array whose index is amount.
If V == 0, then 0 coins required.
If V > 0
minCoin(coins[0..m-1], V) = min {1 + minCoins(V-coin[i])}
where i varies from 0 to m-1
and coin[i] <= V
public int coinChange(int[] coins, int amount) { int res = coinChangeHelper(coins, amount); if(res == Integer.MAX_VALUE ) return -1; else { return res; } } public int coinChangeHelper(int[] coins, int amount) { if(amount == 0) return 0; int res = Integer.MAX_VALUE; if(amount < 0) { return res; } for(int i = 0; i < coins.length; i++) { if(amount>=coins[i]) { int sub = this.coinChangeHelper(coins, amount - coins[i]); if( sub != Integer.MAX_VALUE) { res = Math.min(res, sub + 1); } } } return res; }
Solution: DP
public int coinChangeDP(int[] coins, int amount) { int n = coins.length; int[] dp = new int[amount+1]; dp[0] = 0; for(int i = 1; i <= amount ; i++) { dp[i] = Integer.MAX_VALUE; } for(int i = 1; i <= amount; i++) { for(int j = 0; j < n; j++ ) { if(i >= coins[j]) { if(dp[i-coins[j]] != Integer.MAX_VALUE) { dp[i] = Math.min(dp[i], dp[i-coins[j]] + 1); } } } } if(dp[amount] == Integer.MAX_VALUE) return -1; else return dp[amount]; } }
Comments
Post a Comment