【剑指Offer】7.斐波那契数列(Python实现)

题目描述

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

n<=39

解法一:循环法

# -*- coding:utf-8 -*-
class Solution:
    def Fibonacci(self, n):
        # write code here
        a,b = 0,1
        for i in range(n):
            a,b = b,a+b 
        return a

解法二:动态规划

class Solution:
    def Fibonacci(self, n):
        # write code here
        if n == 0:
            return 0
        preInt = 1
        postInt = 1
        i = 2
        while i < n:
            preInt = preInt + postInt
            postInt = preInt - postInt
            i += 1
        return preInt

解法三:递归法

def Fibonacci(n):
    if n == 0:
        return 0
    if n == 1 or n == 2:
        return 1
    return Fibonacci(n-1)+Fibonacci(n-2)
发布了60 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36936730/article/details/104578348