【发布时间】:2019-07-05 07:03:48
【问题描述】:
我正在尝试使用记忆和递归来解决硬币找零的问题。但是我的代码中有一些小故障,它给了我错误的输出。
public static int coinChangeMemo(int coins[], int n) {
int [][] memo = new int[n+1][coins.length+1];
for (int row = 0; row < memo.length; row++) {
for (int col = 0; col < memo[row].length; col++) {
memo[row][col] =-1;
}
}
return coinChangeMemoHelper(coins, n, 0, memo);
}
private static int coinChangeMemoHelper(int coins[], int n, int index, int memo[][]) {
if(n == 0) {
return 1;
}
if(index >= coins.length) {
return 0;
}
if(n <= 0) {
return 0;
}
if(memo[n][index] != -1) {
return memo[n][index];
}
int withUsingCurrent = coinChangeMemoHelper(coins, n-coins[0], index, memo);
int withoutUsingCurrent = coinChangeMemoHelper(coins, n, index+1, memo);
memo[n][index] = withUsingCurrent + withoutUsingCurrent;
return withUsingCurrent + withoutUsingCurrent;
}
public static void main(String[] args) {
//coins denominations are 1, 2
int coins[] = {1,2};
//i want a change of 4
int sum = 4;
System.out.println(coinChangeMemo(coins, sum));
硬币面额可用 1,2
我想要一个 4 的总和。
可能的方法是
- (1,1,1,1)
- (1,2,1)
- (2,2)
我期待输出 3,但它返回给我 5
【问题讨论】:
-
我不知道你的代码应该做什么,或者为什么它会返回 3。如果你有 1 和 2 的硬币,并且你的金额是 4,我希望它返回 2 2枚硬币
-
@Stultuske 我想返回给定数量 4 的方式数。我已经更新了描述。
-
我的猜测,您的代码将 2,1,1 - 1,1,2 - 1,2,1 视为不同的解决方案。
标签: java recursion memoization