不清楚为什么这个换币算法有效



昨天我和SO的一个人一起工作,让我的换币算法工作。

在我看来,

  1. 首先,makeChange1()调用getChange1(),变化量为…
  2. getChange1()检查amount == 0,如果是,则打印列表
  3. 如果是amount >= current denomination,它将把该面额添加到列表中,然后循环,按当前面额减少金额…
  4. 如果amount < current denomination,它会重复到下一个面额…(index + 1)

我不明白一旦金额等于0,getChange()将如何再次被调用…它不是说如果amount == 0,它就会打印出列表吗?

    if (amount == 0) {
        System.out.print(total + ", ");
    }

因此,正因为如此,我不确定其余的排列将如何完成…一张图片真的很有帮助!

输入

:

12 cents

:

[10, 1, 1], [5, 5, 1, 1], [5, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

:

public void makeChange1(int amount) {
    getChange1(amount, new ArrayList<Integer>(), 0);
}
public void getChange1(int amount, List<Integer> total, int index) {
    int[] denominations = {25, 10, 5, 1};
    if (amount == 0) {
        System.out.print(total + ", ");
    }
    if (amount >= denominations[index]) {
        total.add(denominations[index]);
        getChange1(amount-denominations[index], total, index);
        total.remove(total.size()-1);
    }
    if (index + 1 < denominations.length)   {
        getChange1(amount, total, index+1);
    }
}

谢谢!

它不是else-if,并且该方法在打印出列表后不会返回。

一旦打印出该行,它将继续

if (index + 1 < denominations.length)   {
    getChange1(amount, total, index+1);
}

将以递增的索引再次调用您的函数

最新更新