到目前为止,这是我的代码。我想递归地找到产生给定金额的所有组合。这是应该打印组合的测试程序,但正如我所料,有一个错误
ArrayIndexOutOfBoundsException: 0
在两排。请帮忙,我不明白。以及如何将它们保存到数组而不是打印?
import java.util.Scanner;
public class CoinChange {
public static void printCombos(int sum, int sumSoFar, int[] coinsSoFar) {
int[] coins = {5, 10, 20, 50};
if (sum == sumSoFar) {
System.out.print(coinsSoFar);
}
else if (sum > sumSoFar) {
for (int i = 0; i < 4; i++) {
sumSoFar = sumSoFar + coins[i];
coinsSoFar[coinsSoFar.length] = coins[i]; // error row
printCombos(sum, sumSoFar, coinsSoFar);
}
}
}
public static void main (String[]args) {
Scanner read = new Scanner(System.in);
int sum = read.nextInt();
int[] empty = {};
printCombos(sum, 0, empty); //error row
}
}