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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Java代码如下:
import java.util.Arrays;
public class Solution {
public int coinChange(int[] coins, int amount) {
if(amount == 0) {
return 0;
}
if(coins.length == 0) {
return -1;
}
int[] result = new int[amount + 1];
for(int i = 0; i < result.length; i++) {
result[i] = -1;
}
boolean exist = false;
for(int i = 0; i < coins.length; i++) {
if(coins[i] <= amount) {
result[coins[i]] = 1;
exist = true;
}
}
if(!exist) {
return -1;
}
Arrays.sort(coins);
for(int i = coins[0] + 1; i <= amount; i++) {
if(result[i] == 1) {
continue;
}
int min = Integer.MAX_VALUE;
for(int j = 0; j < coins.length && i - coins[j] >= coins[0]; j++) {
if(result[i - coins[j]] != -1) {
min = min > result[i - coins[j]] + 1 ? result[i - coins[j]] + 1 : min;
}
}
result[i] = min == Integer.MAX_VALUE ? -1 : min;
}
return result[amount];
}
public static void main(String[] args) {
int[] coins = {2147483647};
Solution solution = new Solution();
System.out.println(solution.coinChange(coins, 2));
}
}
5万+

被折叠的 条评论
为什么被折叠?



