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

在这里插入图片描述
裴波那契数列的规律就是第0项为0,第一项为1,从第2项开始后一个等于前两个之和
在这里插入图片描述
利用数学规律递归

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

    }
}

非递归迭代版本

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

    }
}

猜你喜欢

转载自blog.csdn.net/char_m/article/details/109256656