一周刷完剑指offer-7-斐波那契数列

1. 题目描述

大家都知道斐波那契数列,前两项相加为第三项的值

如:0, 1, 1, 2, 3, 5, 8, 13......

2. 示例

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

3. 解题思路

第一种方法:使用递归的形式

第二种方法:使用非递归的形式,不同与python,【a, b = b, a+b】, java需要使用一个中间变量

4. Java实现

使用递归

public class Solution {
    public int Fibonacci(int n) {
        
        if (n <= 0) return 0;
        if (n == 1) return 1;
        
        return (Fibonacci(n-2) + Fibonacci(n-1));
 
    }
}

非递归:

public class Solution {
    public int Fibonacci(int n) {
        
        int a = 0, b = 1;
        int temp;
        for (int i = 0; i < n; i++){
            temp = a;
            a = b;
            b = temp + b;
        }
        
        return a;
 
    }
}

5. Python实现

第一种方法:递归

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

二种方法:非递归

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

如果您觉得本文有用,请点个“在看”

image.png

posted @ 2020-09-17 14:34  蜘蛛侠不会飞  阅读(101)  评论(0编辑  收藏  举报

俺的博客

https://blog.csdn.net/qq_40587575

俺的公众号