def recMC(coinList, change):
minCoins = dic.get(change)
if minCoins:
return minCoins
print("========%s"%change)
minCoins = change
if change in coinList:
minCoins = 1
else:
for j in [i for i in coinList if i < change]:
res = recMC(coinList, change - j) + 1
if minCoins > res:
minCoins = res
dic[change] = minCoins
return minCoins
dic = {}
print(recMC([1,2,5,10,20,50,100], 342))
动态规划算法解决找零问题
def dynamic_change(coinList, change):
for a in range(1, change + 1):
if a in coinList:
dic[a] = 1
else:
minCoins = a
for j in [i for i in coinList if i < a]:
if minCoins > dic[a - j] + 1:
dic[a] = dic[a - j] + 1
dic = {}
dynamic_change([1,2,5,10,20,50,100], 342)
print(dic[342])