剑指Offer-Python-斐波那契数列

题目

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

思路:两种方法,递归和递推。这题的测试环境中不允许用递归,所以以下代码为递推。

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        if n == 0 or n == 1:
            return n
        else:
            res = [0] * (n+1)
            res[1] = 1
            for i in range(2, n+1):
                res[i] = res[i-1] + res[i-2]
            return res[n]

猜你喜欢

转载自blog.csdn.net/qq_34364995/article/details/81136382