求斐波那契数列第N项元素——Java实现(递归、循环)

刚开始刷题,在此记录一下解题思路,以便后期复习。

斐波那契数列

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

Fib(n) = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ……} n = 0,1,2,3,4……n
可以看出从第三个数开始,该数的值等于前两个数值之和
由此可解斐波那契数列:

//循环解法:
public class Solution {
    public int Fibonacci(int n) {
        if(n == 0){
            return 0;
        }else if(n <= 2){
            return 1;
        }
        int a = 1;
        int b = 1;
        int c = 0;
        for(int i=3; i <= n; i++){
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
}
//递归解法
public class Solution {
    public int Fibonacci(int n) {
		if(n == 0){
            return 0;
        }else if(n <= 2){
            return 1;
        }
		return Fibonacci(n-1) + Fibonacci(n-2);
	}
}

猜你喜欢

转载自blog.csdn.net/ly52014/article/details/89210371