I am trying to use recursion to find the minimum number of coins to get a given amount. I have a code that can display the minimum number of coins required, but I canβt find a way to print which coins were used to solve this issue. I searched and found similar examples, but I cannot apply it correctly to this.
Here is what I still have:
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:");
in.close();
}
}
Example code that still works:
Please enter an integer amount.
17
The minimum number of coins to make 17 in United States currency is 4.
The coins used were:
If someone can give me some idea of ββhow to do this, that would be very appreciated.
source
share