我的任务是找到一种显示所有可能的方式的方法,这些方法可以退还给定值的更改,这些值是从txt文件中扫描过来的.这必须通过递归回溯来完成,否则我的解决方案将不获好评.老实说,我完全不知道如何在适当的算法中编码.我所知道的是该算法的工作原理如下:
start with empty sets.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
add a nickel to another (empty) set.
subtract '5' from my amount.
This equals 2; so I'll have to keep working on this set.
Now I'm working with sets that already include one nickel.
add a dime to one set.
subtract '10' from my amount.
This is a negative number, so I discard that set: it is invalid.
repeat this with a nickel; I discard this possibility because (2 - 5) is also negative.
repeat this with a penny; this is valid but I still have 1 left.
repeat this whole process again with a starting set of one nickel and one penny,
again discarding a dime and nickel,
and finally adding a penny to reach an amount of 0: this is a valid set.
Now I go back to empty sets and repeat starting with a nickel, then pennies.
问题是我没有关于如何或从何开始的丝毫线索,仅是必须完成的线索,或者是否有其他解决方案是显而易见的.
到目前为止,这是我的代码:
更新
import java.io.*;
import java.util.*;
import java.lang.*;
public class homework5 {
public static int penny = 1;
public static int nickle = 5;
public static int dime = 10;
public static int quarter = 25;
public static int halfDollar = 50;
public static int dollar = 100;
public static int change;
public static void main(String[] args) throws FileNotFoundException {
ArrayList coinTypes = new ArrayList();
Integer i;
File f = new File (args[0]);
Scanner input = new Scanner(f);
input.nextLine();
while(input.hasNextInt()) {
i = input.nextInt();
coinTypes.add(i);
}
change = coinTypes.get(coinTypes.size()-1);
coinTypes.remove(coinTypes.size()-1);
System.out.println("Found change"); //used for debugging
System.out.println("Change: " + change);
System.out.println(coinTypes);
}
boolean findChange(int change, List coinTypes,
List answerCoins) {
if(change == 0) {
return true;
}
if(change < 0) {
return false;
} else {
for(Integer coin : coinTypes) {
if(findChange(change - coin, coinTypes, answerCoins)){
answerCoins.add(coin);
return true;
}
}
List answer = new ArrayList();
boolean canFindChange = findChange(change, coinTypes, answer);
if(canFindChange) {
System.out.println(answer);
} else { System.out.println("No change found");
}
return false;
}
}
这是我扫描的输入文件
java homework5 hwk5sample1.txt
// Coins available in the USA, given in cents. Change for $1.43?
1 5 10 25 50 100
143
输出值
Found change
Change: 143
[1, 5, 10, 25, 50, 100]
因此,使用我的coinTypes ArrayList中的数字,我需要一个通用的代码算法来显示所有可能的接收方式,例如使用文件中的硬币将143($1.43)换回零钱,所有便士都是最后一种显示方式.
请不要以为我要你写给我算法,我只是想帮忙写一个算法,否则我什么都不会学.谢谢大家的回答或帮助,这对我来说意义非凡!请让我知道我是否错过了任何事情,或者您需要更多信息