python - 动态规划,最小硬币数量

标签 python dynamic-programming coin-change

我一直在研究算法和数据结构https://runestone.academy/runestone/static/pythonds/index.html ,然后我进入了关于动态规划和经典的最小硬币数量问题的部分。给定一个金额,我们必须计算出将其兑换成不同面额的硬币所需的最少数量的硬币。

在本书提出解决问题的代码中,有两行代码我无法弄清楚它们的作用,即使我的生命依赖于它们。

代码在这里:

def recMC(coinValueList,change):
   minCoins = change
   if change in coinValueList:
     return 1
   else:
      for i in [c for c in coinValueList if c <= change]:
         numCoins = 1 + recMC(coinValueList,change-i)
         if numCoins < minCoins:
            minCoins = numCoins
   return minCoins

print(recMC([1,5,10,25],63))

我不明白为什么我们需要这部分:

         if numCoins < minCoins:
            minCoins = numCoins
   return minCoins

我尝试用一​​条语句替换所有 3 行

   return numCoins 

它似乎工作得很好,除了 change == 0 时。我不认为他们在书中写的方式是为了“保护”输入 0,因为这可以更简单地处理。

他们为什么要这样写?

ps:如果重要的话,我正在 python3.5 上运行它......

干杯

最佳答案

chapter 中所述,

If the amount does not match we have several options. What we want is the minimum of a penny plus the number of coins needed to make change for the original amount minus a penny, or a nickel plus the number of coins needed to make change for the original amount minus five cents, or a dime plus the number of coins needed to make change for the original amount minus ten cents, and so on. So the number of coins needed to make change for the original amount can be computed according to the following:

numCoins=min(1+numCoins(originalamount−1),
             1+numCoins(originalamount−5),
             1+numCoins(originalamount−10),
             1+numCoins(originalamount−25))

for 循环中的下面一行正在计算 numCoins 的每个选项。

for i in [c for c in coinValueList if c <= change]:
     numCoins = 1 + recMC(coinValueList,change-i)

循环中的接下来两行将跟踪 numCoins 的最小值:

if numCoins < minCoins:
        minCoins = numCoins

为了便于理解,您可以将该函数重写为:

def recMC(coinValueList,change):
    if change in coinValueList:
        return 1
    else:
        return min([1 + recMC(coinValueList,change-c) for c in coinValueList if c < change])

关于python - 动态规划,最小硬币数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53162852/

相关文章:

python - 如何按pandas中的相似行进行分组

python - 是否有类似 zipper 的功能可以填充到最长的长度?

当按钮单击时 flutter 创建动态文本字段

c++ - 动态规划 : coin change

algorithm - 为什么贪心找零算法对某些币组不起作用?

python - 如何通过检查列表中的子级索引值来过滤 Pandas 数据帧的行?

python - 运行 flask 服务器

algorithm - 将数组拆分为四个框,使框的异或之和最大

.net - 具有动态模型的 Dapper ORM - 如何不返回任何字段而不是 'Field' = NULL?

optimization - SICP做出改变