我正在嘗試使用遞歸來查找製作給定數量的最小硬幣數量。我有能夠列出所需硬幣最小數量的代碼,但我似乎無法找到打印出使用哪個硬幣來提供解決方案的方法。我搜索並找到了類似的例子,但我似乎無法正確地將其應用於此。打印哪些硬幣用於製作給定數量
這裏是我迄今:
import java.util.*;
public class Coins{
public static int findMinCoins(int[] currency, int amount) {
int i, j, min, tempSolution;
min = amount;
for (i = 0; i < currency.length; i++) {
if (currency[i] == amount) {
return 1;
}
}
for (j = 1; j <= (amount/2); j++) {
tempSolution = findMinCoins(currency, j) + findMinCoins(currency, amount - j);
if (tempSolution < min) {
min = tempSolution;
}
}
return min;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] USA =
{1, 5, 10, 25, 50};
System.out.println("Please enter an integer amount.");
int amount = in.nextInt();
int minCoins = findMinCoins(USA, amount);
System.out.println("The minimum number of coins to make " + amount + " in United States currency is " + minCoins + ".");
System.out.println("The coins used were:");
/*Print coins used to find minCoins.*/
in.close();
}
}
代碼運行至今的一個例子:
Please enter an integer amount.
17
The minimum number of coins to make 17 in United States currency is 4.
The coins used were:
如果有人可以給我如何做到這一點一些見解,它會非常感謝。
有什麼可用的硬幣?另外,試着描述它應該如何工作 - 當前代碼對於某些輸入永遠運行(例如,44例如) – chenchuk
關於質量的附註:請考慮源代碼中的命名。這很糟糕。首先,有一些公約;例如類名開始大寫。然後:一個名字應該說出它命名的是什麼。所以,數字是一個數字,並且重視一個價值......嗯?對於實際的問題,你可能想要開始在這裏和那裏使用printlns ...只是爲了打印中間結果;這可能會給你一個線索......在哪裏以及如何添加相關的打印輸出。 – GhostCat
@chenchuk可用的硬幣可以是任何一組整數。對於我發佈的代碼,我只是使用{1,5,10,25,50}。至於結果,它打印出字符串「以美國貨幣制造17的硬幣的最小數目是4」。如果輸入17。我不確定如何在不使用動態編程的情況下以更高的值提高運行時間。 – Sigonious