剑指offer-斐波那契数列

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

n<=39

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

对于第n个台阶来说,只能从n-1或者n-2的台阶跳上来,所以
F(n) = F(n-1) + F(n-2)
斐波拉契数序列,初始条件
n=1:只能一种方法
n=2:两种
#动态规划版
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)
原文地址:https://www.cnblogs.com/laumians-notes/p/9060551.html