Space complexity of recursive algorithm

限于喜欢 提交于 2019-12-03 10:29:34

问题


I was asked at an interview, the efficient way to solve a problem checking for pallindrome.

Now i can do two things:

  1. starting from i = 0 to i = n/2 and comparing ith and n-ith character to be equal.
  2. I can use recursion to check if first and last are same and the rest of the string is a pallindrome.

The second is recursive. My question is what is the difference in the space complexity of an algorithm's recursive and non-recursive versions?


回答1:


Have a read at

  1. http://www.codeproject.com/Articles/21194/Iterative-vs-Recursive-Approaches
  2. Recursion or Iteration?

Basically, a recursive algorithm will add overhead since you store recursive calls in the execution stack.

But if the recursive function is the last line of the call (tail recursion) then there is no additional penalty.

That is of course both algorithms are the same.




回答2:


In theory they have the same space complexity; it largely depends on whether tail recursion can be optimized.

If so, the stack gets replaced at every recursion so it doesn't incur a penalty.



来源:https://stackoverflow.com/questions/10821059/space-complexity-of-recursive-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!