问题
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