I have a brute force solution with backtracking to solve the coin change problem. Currently i get minimum number of coins that can be used. But how could i also return the coins that were actually used? So for example if the amount is 100 then i would like to return [25, 25, 25, 25].
My current code is below:
public class Solution {
public static void main(String[] args) {
Solution s = new Solution();
int coinChange = s.coinChange(0, new int[] { 1, 25, 50 }, 100);
System.out.println(coinChange);
}
public int coinChange(int idx, int[] coins, int amount) {
if (amount == 0){
return 0;
}
if (idx < coins.length && amount > 0) {
int maxVal = amount / coins[idx];
int minCost = Integer.MAX_VALUE;
for (int x = 0; x <= maxVal; x++) {
if (amount >= x * coins[idx]) {
int res = coinChange(idx + 1, coins, amount - x * coins[idx]);
if (res != -1)
minCost = Math.min(minCost, res + x);
}
}
return (minCost == Integer.MAX_VALUE) ? -1 : minCost;
}
return -1;
}
}