美文网首页
lintcode 366.斐波那契数列

lintcode 366.斐波那契数列

作者: cuizixin | 来源:发表于2018-08-28 23:26 被阅读9次

    难度:容易

    1. Description

    366.斐波那契数列

    2. Solution

    • python
      非递归实现,复杂度O(n):
    class Solution:
        """
        @param n: an integer
        @return: an ineger f(n)
        """
        def fibonacci(self, n):
            # write your code here
            if n==1:
                return 0
            elif n==2:
                return 1
            a,b = 0,1
            for i in range(2,n):
                t = a+b
                a = b
                b = t
            return b
    

    递归实现,复杂度O(2^n),会超时:

    class Solution:
        """
        @param n: an integer
        @return: an ineger f(n)
        """
        def fibonacci(self, n):
            # write your code here
            if n==1:
                return 0
            elif n==2:
                return 1
            return self.fibonacci(n-1)+self.fibonacci(n-2)
    

    3. Reference

    1. https://www.lintcode.com/problem/fibonacci/description

    相关文章

      网友评论

          本文标题:lintcode 366.斐波那契数列

          本文链接:https://www.haomeiwen.com/subject/bcpcwftx.html