数据结构题目,关于递归的思想

数据结构题目,关于递归的思想

题目

Li Lei and Han Meimei have different opinions regarding the linear time complexity in the video lecture.对于视频中线性递归的时间复杂度,A、B两位同学有不同的看法。

Li Lei aggrees to the video, the complexity is O(n) because there are n instances each requiring O(1) execution time. A同学赞同视频中的算法,由于单个递归实例需要O(1)时间完成,共有n个实例,所以整个算法的复杂度是O(n)。

However, Han Meimei believes the time for sum(A,n) to be O(n) instead of O(1), since it’s still executing even when calling sum(A,n-1), leading to a total time complexity of (. You agree with 但B同学认为,当sum(A,n)函数中调用sum(A,n-1)时,sum(A,n)仍在执行,因此sum(A,n)的完成时间不是O(1)而是O(n),依此计算,整个算法的复杂度应该为()。请问哪位同学对了?

分析

递归其实与栈关系有相关性,先进后出。
递归的基本思想,是把规模较大的一个问题,分解成规模较小的多个子问题去解决,而每一个子问题又可以继续拆分成多个更小的子问题
最重要的一点就是假设子问题已经解决了,现在要基于已经解决的子问题来解决当前问题;或者说,必须先解决子问题,再基于子问题来解决当前问题
在上一个问题未完全解决时,栈底的代码是不会处于执行状态的哦!

答案

官方解析:
Han Meimei’s belief is not true because the function sum(A,n) is not executing when calling sum(A,n-1). The data associated with it is pushed into the execution stack. To understand the low-level details of recursive calls, you are encouraged to search for further reading materials. B同学认为“函数中调用sum(A,n-1)时,sum(A,n)仍在执行”,实际上这个想法是错误的。当sum(A,n)调用sum(A,n-1)时,sum(A,n)函数中的数据以“函数帧”的形式被压入一个栈中,并没有处于执行状态。关于递归的底层原理,同学们不妨自行搜索相关资料,以进行深入理解。

题目来源:学堂在线,数据结构(春)
部分引用:递归过程的详解(普通递归以及二叉搜索树的遍历递归)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值