Do iterative and recursive versions of an algorithm have the same time complexity?

后端 未结 5 1829
感情败类
感情败类 2020-12-05 20:06

Say, for example, the iterative and recursive versions of the Fibonacci series. Do they have the same time complexity?

5条回答
  •  感情败类
    2020-12-05 20:27

    Yes, if you use exactly the same ideas underlying the algorithm, it does not matter. However, recursion is often easy to use with regard to iteration. For instance, writing a recursive version of the towers of Hanoi is quite easy. Transforming the recursive version into a corresponding iterative version is difficult and error prone even though it can be done. Actually there is theorem that states that every recursive algorithm can be transformed into an equivalent iterative one (doing this requires mimicking the recursion iteratively using one or more stack data structures to hold parameters passed to recursive invocations).

提交回复
热议问题