Given coins of different denominations coins
and a total amount amount
. Write a function to calculate the minimum number of coins required to make up the total amount. If none of the coin combinations 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
Example 2:
Input: coins =[2]
, amount =3
output: -1
Example 3:
输入:coins = [1], amount = 0
输出:0
Example 4:
输入:coins = [1], amount = 1
输出:1
Example 5:
输入:coins = [1], amount = 2
输出:2
prompt:
1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104
package Solution322;
public class Solution {
public int coinChange(int[] coins, int amount) {
int dp[] = new int[amount + 1];
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
dp[i] = amount + 1;
}
for (int coin : coins) {
for (int amt = 1; amt <= amount; amt++) {
if (amt >= coin) {
dp[amt] = Math.min(dp[amt], 1 + dp[amt - coin]);
}
}
}
int minCoinsReq = dp[amount] != amount + 1 ? dp[amount] : -1;
return minCoinsReq;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] coins = { 1, 2, 5 };
int amount = 11;
System.out.println(sol.coinChange(coins, amount));
}
}
Similar topics: 279. Perfect square number