繁体   English   中英

给硬币找零的方法数

[英]Number of ways to give coin change

我正在尝试使用记忆和递归来解决硬币找零问题。 但是我的代码中有一些小故障,它给了我错误的输出。

    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,1)
  3. (2,2)

我期待输出 3,但它返回给我 5

您需要对代码进行 2 处更改:-> 1.您可以将最后 2 个基本情况组合为: if(index==coins.length || n<0){ return 0; 2. 你在递归调用 withUsingCurrent 时犯了错误: UPDATE IT LIKE THIS BELOW int withUsingCurrent = coinChangeMemoHelper(coins, n-coins[index], index, memo);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM