【发布时间】:2019-07-26 08:50:03
【问题描述】:
我目前正在研究 leetcode 上的硬币找零动态编程问题 -- 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
我尝试实现一种自上而下的记忆方法,其中我保留了一个长度数量的数组,其中每个索引代表我可以用来制作该数量的最小硬币数量。
这是我的 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 上遇到了 Time Limit Exceeded。
这是做动态编程的错误方法吗?如果是这样,你能解释一下哪里错了吗?
非常感谢您。
【问题讨论】:
-
您可能应该定义您的特定硬币找零问题,而不是假设其他人知道这个问题。还要提及您为问题中的代码使用的编程语言。在我看来它像 Java,但其他人可能不知道。
-
@ThomasMcLeod 感谢您的建议!问题的链接已经存在,但我也在帖子中包含了问题陈述。我还注意到解决方案是用 Java 编写的。谢谢!
-
我实际上有完全相同的代码和完全相同的问题
标签: dynamic-programming memoization coin-change