【发布时间】:2019-06-27 01:25:41
【问题描述】:
以下函数获取应加总或覆盖金额的最小硬币数量。 例如:如果我有硬币:[6,11] 并且我需要最少硬币才能获得 13 那么答案应该是 2(其中 11、6),这些是硬币的最小数量。
现在我需要打印构成此答案的实际硬币。
private int minCapacity(int capacity[], int total, Map<Integer, Integer> map)
{
// base case
if (total<= 0)
{
return 0;
}
//if map contains the result means we calculated it before. Lets return that value.
if (map.containsKey(total))
{
return map.get(total);
}
// Initialize result
int res = Integer.MAX_VALUE;
for (int i = 0; i < capacity.length; i++)
{
//allResults.add(capacity[i]);
int subRes = minCapacity(capacity, total- capacity[i], map);
System.out.println("total : " + subRes + ", staff: " + capacity[i]);
//if val we get from picking coins[i] as first coin for current total is less
// than value found so far make it minimum.
if (subRes < res)
{
res = subRes;
coinsRes.put(total, capacity[i]);
}
}
res = (res == Integer.MAX_VALUE) ? res : res + 1;
//memoize the minimum for current total.
map.put(total, res);
return res;
}
这是输出:
总数:1 -> 容量:6 总数:18 -> 容量:11 总数:2 -> 容量:6 总计:6 -> 容量:6 总计:7 -> 容量:11 总计:24 -> 容量:6 总计:12 -> 容量:6 总计:13 -> 容量:6
现在公式应该是得到面额是: 循环到:Max(total) - Capacity(total) 直到结果小于或等于零。
面额是:每个容量(总)
【问题讨论】:
-
这对我来说毫无意义。您已将其标记为“背包问题”、“硬币找零”和“动态规划”;但是由于您可以超出目标(11 + 6 > 13),因此您不需要任何这些东西。只需找到最高面额的硬币,并尽可能多地使用它。没有其他硬币是相关的。
标签: algorithm dynamic-programming minimum knapsack-problem coin-change