我正试图让我的硬币改变算法工作…但它输出了奇怪的结果……它应该列出输入美分的所有变化的排列。
输入27美分,printValues(dan.makeChange(27));
得到我:
[[3, 300, 1386, 4720], [3, 300, 1386, 4720], [3, 300, 1386, 4720],etc...
输入7美分得到我:
[[0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10], [0, 0, 3, 10]]
代码:
public List<int[]> makeChange(int change) {
List<int[]> resultsList = new ArrayList<int[]>();
resultsList = changeMaker(change, new int[] {0,0,0,0}, resultsList);
return resultsList;
}
public List<int[]> changeMaker(int change, int[] toAdd, List<int[]> resultsList) {
if (change == 0) {
//if no $, return the list...
resultsList.add(toAdd);
return resultsList;
}
int[] coins = {25, 10, 5, 1};
for (int i = 0; i < coins.length; i++) {
if (coins[i] <= change) {
//temp = {0, 0, 0, 0}
int[] temp = toAdd;
//move to next amount in temp array
temp[i]++;
resultsList = changeMaker(change-coins[i], temp, resultsList);
}
}
return resultsList;
}
调用:
printValues(dan.makeChange(27));
}
public void printValues (List<int[]> results) {
List<String> printable = new ArrayList<String> ();
for (int[] array : results) {
printable.add(Arrays.toString(array));
}
System.out.println(printable);
}
任何想法吗?
我假设您想用这一行复制数组:
int[] temp = toAdd;
然而,要创建一个副本,你必须这样做:
int[] temp = Arrays.copyOf(toAdd, toAdd.length);