recursion: make changes with fewest coins

蹲街弑〆低调 提交于 2019-12-26 03:54:09

问题


I'm studing the data structure and algorithm in python. Here is the classic problem of recursion involving making change with the fewest coins. Here are the codes. What I do not understand is line 2. why do we need minCoins = change? what does line 8-9 mean? can anyone helo explain that? thank you very much for help!

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))

回答1:


minCoins = change: minCoins is initialized with the value of change which is the maximum value that recMC can return as the minimum value of a coin is 1, assuming integer values of coins.

if change in coinValueList: return 1: base case 1 - if some coin has a value of that of change we just need to grab this 1 coin, thus returning 1

for i in [c for c in coinValueList if c <= change]:: The function then loops through all possible values of 1 single coin to

  numCoins = 1 + recMC(coinValueList,change-i): deduct the coin value i from change, add 1 coin to the number of coins needed which is recursively calculated for the leftover change (change-i). This works inductively from the 2 base cases

  if numCoins < minCoins: minCoins = numCoins inside this loop effectively assigns the smallest number of coins possible to minCoins

If change still had the initialized value of minCoins (implying no value c in coinValueList satisfies c <= change), this means that the number of coins needed is also the value of change, i.e. change 1-unit coins. This is base case 2 that is based on the pre-condition that the coin with value 1 is always available.



来源:https://stackoverflow.com/questions/40088908/recursion-make-changes-with-fewest-coins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!