下午好,
我目前正在开发一个程序,该程序应该使用回溯算法来找到达到一定数量所需的硬币总数的解决方案。
程序的基本布局是这样的
User is prompted for an amount (ie. 123)
int amount = input.nextInt();
User is prompted for number of coins (ie. 6)
int numCoins = input.nextInt();
User is prompted for coin values (ie. 2, 4, 32, 51, 82)
int[] array = new array[] {2, 4, 32, 51, 82};
根据这些信息,我将开发一种回溯算法来输出解决方案。
我试图查找回溯信息无济于事。对我来说,这一切似乎都不清楚我应该从算法开始的地方。
任何帮助表示赞赏。
编辑
这是我目前一直在做的事情......目前无法正常工作
public class coins
{
public static int[] coinValues;
public static int currentAmount = 0;
public static void main(String[] args)
{
ArrayList<Integer> temp = new ArrayList<>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter the amount: ");
int amount = input.nextInt();
System.out.println("Please enter the number of coins: ");
int numCoins = input.nextInt();
coinValues = new int[numCoins];
for (int i = 0; i < numCoins; i++)
{
System.out.println("Please enter coin value of " + i + " :");
int value = input.nextInt();
coinValues[i] = value;
}
for (int i = 0; i < coinValues.length; i++)
{
System.out.print("Coin Value: " + i + " " + coinValues[i] + "\n");
}
tryThis(temp, amount);
for (int i = 0; i < temp.size(); i++)
{
System.out.println(temp.get(i) + " " + " ");
}
}
public static ArrayList<Integer> tryThis(ArrayList<Integer> list, int amount)
{
if (isValid(list, amount) == false)
{
while (amount > currentAmount && (amount > 0))
{
for (int i = 0; i < coinValues.length; i++)
{
for (int k = coinValues.length - 1; k > 0; k--)
{
list.add(coinValues[k]);
int currentCoin = list.get(i);
if (amount > currentAmount)
{
amount = amount - currentCoin;
System.out.println("Amount: " + amount);
}
tryThis(list, amount);
}
}
}
}
return new ArrayList<>();
}
public static boolean isValid(ArrayList list, int amount)
{
boolean keepGoing = true;
if (amount > currentAmount)
{
return keepGoing = false;
}
else
{
return keepGoing;
}
}
}
问候,迈克