我正在嘗試Java硬幣更改問題以枚舉所有可能的更改集。Java遞歸硬幣更改嘗試
我的邏輯如下這樣:
while n >= denom m {
array[]+= denom m
n-= denom m
}
list.add[array[]]
return coinChanger(++denom)
我的代碼:
public List<Integer> makeChange(int change) {
int[] denominations;
denominations = new int[]{1, 5, 10, 25};
return changeMaker(change, denominations, 0);
}
public List<Integer> changeMaker(int change, int[] denominations, int index) {
List<Integer> resultsList = new ArrayList<Integer>();
int[] resultDenom;
resultDenom = new int[4];
if (change <= 1) {
return resultsList;
}
while (change >= denominations[index]) {
resultDenom[index] += denominations[index];
System.out.println("ResultsDenom: " + resultDenom[index]);
change -= denominations[index];
}
resultsList.add(resultDenom[index]);
for (int val : resultDenom) {
System.out.println(val);
}
if (change > denominations[index]) {
return changeMaker(change-=denominations[index], denominations, ++index);
}
return resultsList;
}
該輸出僅1組的所有枚舉:
OUTPUT:
27
0
0
0
RESULT CHANGE PERMUTATIONS LIST: [27]
個
問題:
我竭力要弄清楚如何移動到下一面額,一旦其中一人完成...我知道你應該移到面額數組中的下一個索引...但是那只是增加了下一枚硬幣......我如何使它增加下一枚最大的硬幣,然後遞歸地下降到下一枚硬幣......一直穿過所有4枚硬幣?
謝謝!
* 編輯 **
public List<Integer> makeChange(int change) {
int[] denominations;
denominations = new int[]{25, 10, 5, 1};
return changeMaker(change, denominations, 0);
}
public List<Integer> changeMaker(int change, int[] denominations, int index) {
List<Integer> resultsList = new ArrayList<Integer>();
int[] resultDenom;
resultDenom = new int[4];
if (change <= 1) {
return resultsList;
}
if (index > 3) {
return resultsList;
}
//if 27 >= 25
if (change >= denominations[index]) {
//[+25, 0, 0, 0]
resultDenom[index] += denominations[index];
//{ LIST } <--- [25, 0, 0, 0]
//List now contains { [25, 0, 0, 0], }, still need all other permutations
resultsList.add(resultDenom[index]);
//27 - 25,
return changeMaker(change-=denominations[index], denominations, ++index);
}
return resultsList;
}
所需的輸出:列出清單...... 27美分:
LIST{ [1, 0, 0, 2], [0, 2, 1, 2], [0, 1, 3, 2]... etc}
是你的整個輸出? System.out.println(「ResultsDenom:」+ resultDenom [index]);'? – noMAD 2013-05-10 19:41:41
如果你的輸入是'27',並且你沒有任何改變就使用了上面的代碼,那麼輸出就不能成爲你的輸入。 – noMAD 2013-05-10 19:43:22
http://stackoverflow.com/search?q=coin+change ... – 2013-05-10 19:43:23