描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0,第1项是1)。
n ≤ 39
示例1
输入:
4
返回值:
3
解题思路
一上来拿到这道题,心里想的第一句就是:斐波那契数列,我不太记得你了
知识点复习
斐波那契数列公式为:f[n] = f[n-1] + f[n-2], 初始值f[0]=0, f[1]=1,目标求f[n]。
这个数列从第3项开始,每一项都等于前两项之和。
法一:有公式就可以用 递归:
public class Solution {
public int Fibonacci(int n) {
if(n==0||n==1){
return n;
}
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 first = 0;
int second = 1;
int third = 0;
for(int i=2; i<=n; i++){
third = first + second;
first = second;
second = third;
}
return third;
}
}