要实现斐波那契数列,首先先要了解什么是斐波那契数列
0 ,1,1,2,3,5,8,13…
1,1,2,3,5,8,13…
从0或1开始这样的数列称为斐波那契数列这样的数列称为斐波那契数列
我们讲下1,1,2,3,5,8,13…该如何计算
通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
给定 N,计算 F(N)
递归方式:
class Solution {
public int fib(int N) {
if(N < 1){
return 0;
}
if(N == 1){
return 1;
}
return fib(N-1) + fib(N-2);
}
}
非递归方式:
class Solution {
public int fib(int N) {
if(N < 1){
return 0;
}
if(N == 1){
return 1;
}
if(N == 2){
return 1;
}
int pre1=1;
int pre2=1;
int curr=0;
for(int i=3; i<=N; i++){
curr=pre1+pre2;
pre1=pre2;
pre2=curr;
}
return curr;
}
}