硬币找零的方法数量

时间:2019-07-05 07:03:48

标签: java recursion memoization

我正在尝试使用备忘录和递归解决硬币找零的问题。但是我的代码中出现了一些小故障,这给了我错误的输出。

    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

1 个答案:

答案 0 :(得分:1)

您需要在代码中进行2处更改:->     1.您可以将最后两个基本情况组合为:     if(index == coins.length || n <0){     返回0;     }     2.您在递归调用withUsingCurrent时犯了错误:     像下面这样更新     int withUsingCurrent = coinChangeMemoHelper(coins,n-coins [index],index,memo);