0
無法找到問題,當我運行這段代碼不言而喻計算器每次由於此行硬幣兌換在Java代碼中的StackOverflowError
countCombine += count(array,money - (array[i]*(int)(money/array[i])));
主要問題是很容易的。 給定值N,如果我們想做出改變對於N美分,而我們每一個的無限供給S = {S1,S2,...,SM}價值的硬幣,有多少種方法可以使我們的變化?硬幣的順序無關緊要。
例如,對於N = 4且S = {1,2,3},有四種方案:{1,1,1,1},{1,1,2},{2,2} ,{1,3}。因此輸出應該是4.對於N = 10和S = {2,5,3,6},有五種解決方案:{2,2,2,2,2},{2,2,3,3}, {2,2,6},{2,3,5}和{5,5}。所以輸出應該是5
public class CoinExchangeProblem {
int countCombine = 0;
private int count(int array[],int money){
// sort the array
// Arrays.sort(array);
// System.out.println(Arrays.toString(array));
if (money == 0) {
return 1;
} else if (money < 0) {
return 0;
}
for(int i = 0; i < array.length; i++){
countCombine += count(array,money - (array[i]*(int)(money/array[i])));
}
return countCombine;
}
public static void main(String[] args) {
CoinExchangeProblem coinExch = new CoinExchangeProblem();
System.out.println(coinExch.count(new int[]{1,2,3}, 4));
// System.out.println(coinExch.count(new int[]{2, 5, 3, 6}, 10));
}
}
你有沒有在IDE調試器中運行呢?如果沒有,儘快這樣做。 –
是我試過的調試,我認爲「的for(int i = 0;」這是問題的原因 – dayitv89
你必須做更多的'如果(錢<0)'不僅僅是返回0,你需要改變一下程序。包括讓它嘗試另一種價值的硬幣,但更重要的是,遞歸的邏輯必須在試圖將其提交給代碼之前在紙面上進行思考和測試,並且您需要找到一種方法來返回多個解決方案或打印出多種解決方案。 –