我目前正在力扣上做找零钱动态规划问题 -- https://leetcode.com/problems/coin-change/。
以下是问题说明:
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 = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
Example 2:
Input: coins = [2], amount = 3
Output: -1
我尝试使用自顶向下的记忆化方法,其中我保留一个长度为amount的数组,其中每个索引表示我可以使用的最少硬币数来凑成该金额。
以下是我在Java中的代码:
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
int min = coinChange(coins, amount, dp);
return min == Integer.MAX_VALUE ? -1 : min;
}
private int coinChange(int[] coins, int amount, int[] dp) {
if (amount < 0) {
return Integer.MAX_VALUE;
}
if (amount == 0) {
return 0;
}
if (dp[amount] != Integer.MAX_VALUE) {
return dp[amount];
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < coins.length; i++) {
int val = coinChange(coins, amount - coins[i], dp);
if (val != Integer.MAX_VALUE) {
min = Math.min(min, val + 1);
}
}
dp[amount] = min;
return min;
}
}
我认为这是解决这个问题的正确动态规划方法,但是在LeetCode上却遇到了超时错误。
这种动态规划方法是否错误?如果是,请说明它错在哪里。
非常感谢您的帮助。