【发布时间】:2021-05-27 18:53:56
【问题描述】:
这两个递归函数之间的速度差异很大,我不明白为什么。这些是来自 Google Foobar 的“The Grandest Staircase of Them All”的解决方案。本质上,您需要确定有多少个可能的楼梯可以用 n 个块组成(一个楼梯是一个自然数序列,其中每个数字都比前一个数字高,至少有两个“步骤” - 例如,[1, 2 , 3] 是一个由 6 个方块组成的楼梯)。
这是我写的代码:
def solution(n):
return stairs(n, n)
def stairs(lastStair, n):
if (n < 1):
return (1 if n == 0 else 0)
if (lastStair == 1):
return 0
#recursively call stairs() for each possible next step height, and add the results together
return sum([stairs(i, n - i) for i in range(1, lastStair)])
print(solution(200))
这是别人写的(取自here):
from functools import lru_cache
@lru_cache(maxsize=None)
def count(height, left):
if left == 0:
return 1
if left < height:
return 0
return count(height + 1, left - height) + count(height + 1, left)
print(count(1, 200) - 1)
两者都给出正确的结果。但是,我的版本要慢得多。在我的计算机上,当 n = 200 时,solution(n) 需要大约两个小时才能运行,而 count(1, n) 需要不到一秒。我将缓存代码添加到我的并且运行时保持不变。是什么导致解决方案(200)需要 10,000 倍的时间?或者,也许正确的问题是,为什么缓存对解决方案没有好处(200)?
【问题讨论】:
标签: python recursion caching optimization runtime