【问题标题】:Minimum Coin Change (Infinite, Unbound) Print the values最小硬币变化(无限,未绑定)打印值
【发布时间】: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


【解决方案1】:

记住capacity[i] 或索引i 的哪个项目是最好的subres

将其存储在地图的附加字段中。

最后展开地图中的最佳序列。

【讨论】:

  • 如何展开最佳序列。您能否提供有关您的答案的 sn-p 以进行更多说明。非常感谢
  • 您的最终结果映射条目 map.get(sum); 包含硬币数量 (res) 和最后一个达到此结果的硬币 (coin)。现在转到 sum-coin 条目并重复直到 0
  • 我尝试应用您的建议(谢谢),但这导致我回答错误。 (如果我错了,请纠正我的代码) if (subRes
  • 容量[i] 值应该对应于总键,而不是对应于 res
  • 我更新了帖子。如果我错了,请纠正我或确认。
猜你喜欢
  • 2011-05-11
  • 2017-10-28
  • 2016-01-24
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
相关资源
最近更新 更多