【发布时间】:2018-02-03 17:39:37
【问题描述】:
问题是使用动态规划编写一个函数来计算爬 N 步的方法数。鉴于一次只能爬 1 级或 2 级。
例如,如果 N=3,则函数应返回 [(1,1,1),(1,2),(2,1)]。 我在 python 3 中编写了一个代码来计算。代码运行良好,但与不使用动态编程的相同递归代码相比,当 N 增加到 40 时,它需要相同的时间或 spyder(Anaconda) 应用程序崩溃。
不应该比普通的效率高吗?
我在下面附上了 DP 代码
def stepsdyn(N,memo={}):
"""
L1 is the list of all possibilities in the left side of the search tree,
that is with 1 as the last element
L2 is the list of all possibilities in the right side of the search tree
memo stores the results of corresponding N
returns memo[N]
"""
L1=[]
L2=[]
if N==1:
return [(1,)]
elif N==0:
return [()]
else:
try:
return memo[N]
except:
for items in stepsdyn(N-1,memo):
items+=(1,)
L1.append(items)
for items in stepsdyn(N-2,memo):
items+=(2,)
L2.append(items)
memo[N]=L1+L2
return memo[N]
【问题讨论】:
-
你说它崩溃是什么意思?有一些错误信息吗?它只是不返回任何东西/需要很长时间吗?
-
@PatrickHaugh 是的,它需要很长时间然后崩溃,也就是说它被挂起(没有响应),我必须重新启动我的电脑。对于不超过 30 的数字,它可以正常工作,但与没有动态编程的普通递归代码所花费的时间几乎相同
标签: python dynamic-programming memoization search-tree