|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
【求助帖】请及时确认最佳答案,下次提问时可以得到更多关注,问题可以更快解决
def money(ownmoney, moneylist,knownlist):
if ownmoney in moneylist:
knownlist[ownmoney] = 1
return 1
#如果ownmoney 已经在列表中存在其最小硬币数,如3,我就不用再递归啦,直接调用器最小硬币数,也是结束递归的条件
elif knownlist[ownmoney] >0:
return knownlist[ownmoney]
else:
for each in [c for c in moneylist if c <= ownmoney]:
numbercoin = 1 + money(ownmoney - each, moneylist,knownlist)
if knownlist[ownmoney] == 0:
knownlist[ownmoney] = numbercoin
return numbercoin
print(money(40,[1,5,10,25],[0]*63))
def money(ownmoney, moneylist, knownlist):
if ownmoney in moneylist:
knownlist[ownmoney] = 1
return 1
elif knownlist[ownmoney] > 0:
return knownlist[ownmoney]
else:
min_coins = float('inf') # 初始化最小硬币数为正无穷
for each in [c for c in moneylist if c <= ownmoney]:
numbercoin = 1 + money(ownmoney - each, moneylist, knownlist)
if numbercoin < min_coins:
min_coins = numbercoin
knownlist[ownmoney] = min_coins # 将最小硬币数存储在knownlist中
return min_coins
print(money(40, [1, 5, 10, 25], [0] * 41))
上面两段代码有什么区别,为什么要用min_coins 保存numbercoins变量,print的输出结果也不同 |
|