python学习之找零问题(递归和动态规划两种解法)
Posted 今夜月色很美
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习之找零问题(递归和动态规划两种解法)相关的知识,希望对你有一定的参考价值。
递归解决找零问题
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])
以上是关于python学习之找零问题(递归和动态规划两种解法)的主要内容,如果未能解决你的问题,请参考以下文章