硬币改变 - 所有解决方案递归 - Java

时间:2017-05-18 09:16:02

标签: java recursion

我正在尝试找到coin change problem的所有可能解决方案。

示例:我有可用的硬币1和2,我想要更改6。

正确解决方案: [1,1,1,1,1,1],[2,1,1,1,1,0],[2,2,1,1, 0,0],...

我的代码: [1,1,1,1,1,1],[1,1,1,1,0,0],[1,1,0,0, 0,0],...

最后一行还会删除我的参数“coinsSoFar”,我不明白为什么。当我调试时,它将temp设置为[0,0,0,0,0,0] AND coinsSoFar为[0,0,0,0,0,0],它应该保持在[2,0,0,0, 0,0]。

非常感谢您的帮助。 (clearArray:所有数字都设置为0; addToArray:将前0替换为数字)

    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?

    }
}

2 个答案:

答案 0 :(得分:1)

当你这样做时

ul {
  list-style-type: none;
  padding: 0;
  margin-bottom: 15px;
}

li {
  padding-left: 10px;
  padding-bottom: 0.1em;
  text-indent: -.5em;
}

li:before {
  content: "– ";
  color: #333;
}

您正在设置temp以引用与int[] temp = coinsSoFar; 相同的数组。因此,您对coinsSoFar所做的任何事情都会影响temp

如果您希望coinsSoFar引用temp副本,请执行以下操作:

coinsSoFar

答案 1 :(得分:0)

您使用clearArray(temp, 0)清除原始数组 - 按引用传递。

调用int[] temp = coinsSoFar;您不会创建数组的副本,而是创建对同一数组的引用。

也应该是|| amount <= 0

相关问题