栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

您如何找到这种递归函数的空间复杂性?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

您如何找到这种递归函数的空间复杂性?

让我们想象一下对f(4)进行评估(您考虑的示例)。这是怎么回事。堆栈从看起来像

I need to compute f(4)

然后f(4)的计算返回到f(3),堆栈看起来像

I need to compute f(4), so I need to compute f(3)

然后我们继续下降,最终到达

I need to compute f(4), so I need to compute f(3), so  I need to compute f(2), so   I need to compute f(1), so    I need to compute f(0)

然后,我们可以将f(0)计算为1,最后一次调用返回。倒数第二个调用(用于计算f(1)的那个),然后要计算f(0)的第二个副本,堆栈将转到:

I need to compute f(4), so I need to compute f(3), so  I need to compute f(2), so   I need to compute f(1), and although I've already computed the first f(0)=1, I still need to compute the second occurrence of f(0), so    I need to compute f(0) (again)

然后返回,因此f(1)的计算可以返回,我们得到

I need to compute f(4), so I need to compute f(3), so  I need to compute f(2), and although I've already computed the first f(1)=2, I still need to compute the second occurrence of f(0)

从那里堆栈变成:

I need to compute f(4), so I need to compute f(3), so  I need to compute f(2), and although I've already computed the first f(1)=2, I still need to compute the second occurrence of f(0), so...   I need to compute f(1)

它将继续像以前一样计算f(1)。

关键是,即使(最终)将执行2 ^ n次运算,堆栈也只能达到n的深度。因此,时间复杂度为O(2 ^ n),但空间复杂度仅为O(n)。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/383023.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号