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:
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Input: coins = [2], amount = 3
Output: -1
Note:
You may assume that you have an infinite number of each kind of coin.
解釋下題目:
1. 動態規劃
實際耗時:xxms
public int coinChange(int[] coins, int amount) {
if (amount < 1) {
return 0;
}
int[] dp = new int[amount];
return helper(coins, amount, dp);
//System.out.println(Arrays.toString(dp));
}
private int helper(int[] coins, int left, int[] dp) {
if (left < 0) {
return -1;
}
if (left == 0) {
//found the answer
return 0;
}
if (dp[left - 1] != 0) {
return dp[left - 1];
}
int min = Integer.MAX_VALUE;
for (int coin : coins) {
int tmp = helper(coins, left - coin, dp);
if (tmp >= 0) {
if (tmp < min) {
min = tmp + 1;
}
}
}
dp[left - 1] = (min == Integer.MAX_VALUE ? -1 : min);
return dp[left - 1];
}
踩過的坑:[186,419,83,408],6249 這組。
??首先確定這題絕對不是貪心。然后其實如果你知道amount = 500怎么求的話,其實500以下的所有數字你也知道怎么求了。然后算法有個出口,我之前搓一直錯在這里,就是如果dp[left - 1] != 0
,這里我之前寫的是大于,其實如果是-1也算找到了答案,所以要改成不等于0,其他的應該就沒難度了。