牛客网 斐波那契数列

剑指offer 牛客网 斐波那契数列

# -*- coding: utf-8 -*-
"""
Created on Mon Apr  8 15:35:14 2019

@author: Administrator
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39

"""

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        if n == 0:
            return 0
        if n == 1:
            return 1
        if n == 2:
            return 1    
        if n >= 3:
            res = []
            res.append(1)
            res.append(1) #加入最初始的两个值[1,1]
            for i in range(2,n):    #从第二个数开始,加入前两个值相加
                res.append(res[i-1]+res[i-2])
            return res[n-1] #只返回最后一个数
            
        
if __name__ == '__main__':
    solution = Solution()
    n = 39
    res = solution.Fibonacci(n)
    print(res)
原文地址:https://www.cnblogs.com/missidiot/p/10671184.html