coin change - all solutions recursive - Java

泪湿孤枕 提交于 2019-12-25 09:27:52

问题


I am trying to find all possible to solutions to the coin change problem.

Example: I have the coins 1 and 2 available and I want to change 6.

Right Solution: [1,1,1,1,1,1], [2,1,1,1,1,0], [2,2,1,1,0,0], ...

My Code: [1,1,1,1,1,1], [1,1,1,1,0,0], [1,1,0,0,0,0], ...

The last line also deletes my parameter "coinsSoFar" and I don't understand why. When I debug it sets temp to [0,0,0,0,0,0] AND coinsSoFar to [0,0,0,0,0,0], which should stay at [2,0,0,0,0,0].

Would be very thankful for help. (clearArray: all numbers set to 0; addToArray: replace first 0 with number)

    public static void makeChange(int amount, int startCoinIndex, int[] coinsSoFar) {

    if (amount == 0) {
        System.out.println(Arrays.toString(coinsSoFar));
    }

    if (startCoinIndex == coinSet.length || amount < 0) {return;}

    for (int i = 0; i * coinSet[startCoinIndex] <= amount; i++) {

        int[] temp = coinsSoFar;

        for (int j = 0; j < i; j++) {
            addToArray(temp, coinSet[startCoinIndex]);
        }

        makeChange(amount - i * coinSet[startCoinIndex], startCoinIndex+1, temp);
        clearArray(temp);  // this line also clears coinsSoFar. Why?

    }
}

回答1:


You clear original array with the clearArray(temp, 0) - pass by reference.

Calling int[] temp = coinsSoFar; you don't create a copy of the array but a reference to the same array.

Also should be || amount <= 0




回答2:


When you do

int[] temp = coinsSoFar;

you are setting temp to reference the same array as coinsSoFar. So anything you do to temp now affects coinsSoFar.

If you meant for temp to refer to a copy of coinsSoFar, here's what to do:

int[] temp = Arrays.copyOf(coinsSoFar, coinsSoFar.length);
//  OR, if you prefer
int[] temp = new int[coinsSoFar.length];
System.arraycopy(coinsSoFar, 0, temp, 0, coinsSoFar.length);


来源:https://stackoverflow.com/questions/44043531/coin-change-all-solutions-recursive-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!