Given coins of different denominations and a total amount. Write a function to calculate the minimum number of coins required to make up the total amount. If no coin combination can make up the total amount, return -1.
You can think that the number of each coin is unlimited.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
For beginners of dynamic programming, from small to large, the
dp array records each 0,1...,n-2,n-1. The minimum number of coins required for each total amount of these
numbers is dp[ i-coin]+1; (coin is the coin amount, here is calculated by traversing all the gold coin quotas)
class Solution {
public int coinChange(int[] coins, int amount) {
int dp[] = new int[amount+1];
Arrays.fill(dp,amount+1);
dp[0] = 0;
for(int i=1;i<=amount;i++){
for(int s:coins){
if(s<=i){
dp[i] = Math.min(dp[i],dp[i-s]+1);
}
}
}
return (dp[amount]==amount+1)?-1:dp[amount];
}
}