牛客网《剑指offer》之Python2.7实现:斐波那契数列

题目描述

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

思路

1、老方法递归
直接干了一个普通递归,但是系统判超时

2、 迭代

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        if n is 0 or n is 1:
            return n
        a = 1
        b = 1
        while n > 2:
            temp = a
            a += b
            b = temp
            n -= 1
        return a

3、他山之石
评论区看到一个巧妙的利用python列表增长的方法,简洁优美

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        res=[0,1,1,2]
        while len(res)<=n:
            res.append(res[-1]+res[-2])
        return res[n]

猜你喜欢

转载自blog.csdn.net/ck_101/article/details/82695840