1

I worked with someone yesterday from SO on getting my coin changing algorithm to work.

It seems to me that,

  1. first, makeChange1() calls getChange1() with the change amount...
  2. getChange1() checks if amount == 0, if so, it will print the list
  3. if amount >= current denomination, it will add that denomination to the list then recur, decrementing the amount by the current denomination...
  4. if amount < current denomination, it recurs on to the next denomination... (index + 1)

I don't understand how getChange() will be called again once the amount equals 0... doesn't it just say that if amount == 0, it will just print out the list?

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

Therefore, because of this I'm not sure how the rest of the permutations will be completed... A picture would reallly help!

Input:

12 cents

Output:

[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]

Code:

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);
    }
}

Thanks!

4

1 回答 1

2

It's not an else-if and the method doesn't return after printing out the list.

Once it prints out the line, it will continue to

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

Which will call your function again with an incremented index.

于 2013-05-14T15:15:56.827 回答