1

斐波那契数列

描述
大家都知道斐波那契数列,现在要求输入一个正整数 n ,请你输出斐波那契数列的第 n 项。斐波那契数列是一个满足
\(fib(x) = \left\{\begin{matrix} 1 & x = 1,2\\ fib(x-1) + fib(x-2) & x >2 \end{matrix}\right.\)的数列.
数据范围:\(1\le n \le 40\)
要求:空间复杂度\(o(1)\),时间复杂度\(o(n)\).

提示:利用列表计算

class Solution:
    def Fibonacci(self , n: int) -> int:
        # write code here
        z = [0, 1]
        while len(z) <= n:
            z.append(z[-2] + z[-1])
        return z[-1]
        
posted @ 2024-04-01 15:45  Bonne_chance  阅读(22)  评论(0)    收藏  举报
1