3递归(动态规划思想)

Posted aluosen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3递归(动态规划思想)相关的知识,希望对你有一定的参考价值。

# -*- 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递归(动态规划思想)的主要内容,如果未能解决你的问题,请参考以下文章

递归与动态规划

动态规划算法的套路,动态规划入门

一文彻底理解动态规划套路

算法导论—分治法思想动态规划思想贪心思想

动态规划

递归详解