【发布时间】:2018-11-28 23:43:00
【问题描述】:
我有一个带有回溯的蛮力解决方案来解决硬币找零问题。目前我得到了可以使用的最小数量的硬币。但是我怎么还能退还实际使用的硬币呢?因此,例如,如果金额是 100,那么我想返回 [25, 25, 25, 25]。
我当前的代码如下:
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;
}
}
【问题讨论】:
-
您只需要与 minCost 一起跟踪它,并更改您的 minCost 更新行,以便您知道何时更改了 minCost,然后也更新您的 minCoinsUsed。根据您的要求,您可能希望将其存储为列表,以便您可以例如当长度相同时返回多个硬币组合。
-
实际上你的问题是关于如何将这个状态与 minCost 一起传递,因为你通过返回它来传递它?您可以通过引用 coinChange 的所有调用来传递一个对象并将状态存储在那里,或者因为您为每次搜索都有一个新的解决方案对象,您甚至可以将状态存储在其中。
-
只需要返回一个结果。您能否通过与 minCost 一起跟踪来发布代码 sn-p 的含义?
标签: java coin-change