码迷,mamicode.com
首页 > 其他好文 > 详细

3、递归(动态规划思想)

时间:2020-05-02 20:46:19      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:range   OLE   改进   string   odi   code   调用   convert   自身   

# -*- coding:utf-8 -*-
#@Time : 2020/5/2 11:06
#@Author: Aluosen
#@File : Recurrence.py
##进制转换
def toStr(n,base):
convertString = ‘0123456789ABCDEF‘
if n < base:
return convertString[n]
else:
return toStr(n//base,base) + convertString[n%base]
print(toStr(65536,16))

#汉诺塔问题
def moveTower(height, fromPole, withPole, toPole):
if height >= 1:
moveTower(height - 1, fromPole, toPole, withPole)
moveDisk(height, fromPole, toPole)
moveTower(height - 1, withPole, fromPole, toPole)

def moveDisk(disk, fromPole, toPole):
print(f‘Movin disd[{disk}] from {fromPole} to {toPole}‘)
moveTower(3,‘#1‘,‘#2‘,‘#3‘)

技术图片

 

 



#零钱兑换问题-1、递归解法
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

#零钱兑换问题-2、递归解法改进(增加了最优解表,中间结果记录)
def recMC(coinValueList,change,knownResults):
minCoins = change
if change in coinValueList: #最小规模,递归基本结束
knownResults[change] = 1 #记录最优解
return 1
elif knownResults[change] > 0:
return knownResults[change] #查表成功
else:
for i in [c for c in coinValueList if c <= change]: #调用自身
numCoins = 1 + recMC(coinValueList, change - i,knownResults) #减小规模
if numCoins < minCoins:
minCoins = numCoins
#找到最优解,记录到表中
knownResults[change] = minCoins
return minCoins

#零钱兑换问题-3、动态规划算法
def dpMakeChange(coinValueList, change, minCoins):
for cents in range(1, change + 1):
coinCount = cents
for j in [c for c in coinValueList if c <= cents]:
if minCoins[cents -j] + 1 < coinCount:
coinCount = minCoins[cents -j] +1
minCoins[cents] = coinCount
return minCoins[change]

3、递归(动态规划思想)

标签:range   OLE   改进   string   odi   code   调用   convert   自身   

原文地址:https://www.cnblogs.com/Aluosen/p/12819387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!