题目
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)函数中的数据以“函数帧”的形式被压入一个栈中,并没有处于执行状态。关于递归的底层原理,同学们不妨自行搜索相关资料,以进行深入理解。
题目来源:学堂在线,数据结构(春)
部分引用:递归过程的详解(普通递归以及二叉搜索树的遍历递归)