我的程序的目标是输出给定金额的所有可能的变更解决方案,例如
期望的输出
Change: 9
[1, 1, 1, 1, 5]
[1, 1, 1, 1, 1, 1, 1, 1, 1]
(9 = $0.09)但是我的输出有点不同,我的输出看起来像这样
我的输出
Change: 9
[1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 5]
[1, 1, 1, 5, 1]
[1, 1, 5, 1, 1]
[1, 5, 1, 1, 1]
[5, 1, 1, 1, 1]
如您所见,它从字面上为我提供了所有可能的解决方案。我只关心前两个答案。很明显,当要求更大的数量时,这将是一个大问题。所以这是我的问题:根据我的代码,如何将其修复到每个仅显示一个组合的位置?
代码
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int change;
public static void main(String[] args)
throws FileNotFoundException { //begin main
ArrayList<Integer> coinTypes = new ArrayList<Integer>();//array to store
//coin types
ArrayList<Integer> answerCoins = new ArrayList<Integer>(); //to contain solutions
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f); //initialize scanner
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i); //add all ints to file
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Change: " + change);
findChange(change, coinTypes, answerCoins);
}
private static void findChange(int change, List<Integer> coinTypes,
List<Integer> answerCoins) { //contains means of
//finding the change solutions
if(change == 0) {
//base case
System.out.println(answerCoins);
}
else if(change < 0) {
//if negative it can't be a solution
} else {
for(int coin = 0; coin < coinTypes.size(); coin++) {
answerCoins.add(coinTypes.get(coin)); //choose
findChange(change-coinTypes.get(coin), coinTypes, answerCoins);//explore
answerCoins.remove(answerCoins.size()-1); //un-choose
}
}
}
}
感谢您的任何和所有答案,请尽量忽略任何其他错误,我想先解决这个问题。谢谢!!