Tail Recursion Fibonacci

前端 未结 4 1630
清歌不尽
清歌不尽 2020-12-28 18:53

How do I implement a recursive Fibonacci function with no loops running in O(n)?

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 19:48

    Typically I'd be against posting an answer to a homework question like this, but everything posted so far seems to be overcomplicating things. As said in the comments above, you should just use recursion to solve the problem like you would do iteratively.

    Here's the iterative solution:

    def fib(n):
      a, b = 0, 1
      while n > 0:
        a, b = b, a+b
        n -= 1
      return a
    

    Here's an equivalent recursive solution:

    def fib(n):
      def fib_help(a, b, n):
        return fib_help(b, a+b, n-1) if n > 0 else a
      return fib_help(0, 1, n)
    

    Note that in both cases we actually compute up to Fn+1, but return Fn as the result. This fits nicely with the "hint" you were given.

    I hope that you'll take the time to compare the two solutions and convince yourself that they're equivalent. Understanding how to transform an iterative solution to an equivalent recursive one (or vice versa) is a good skill to develop.

提交回复
热议问题