大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
fib(1) = 1
fib(2) = 1;
fib(3) = fib(1)+fib(2);
fib(4) = fib(2)+fib(3);
fib(n) = fib(n-2)+fib(n-1);
递归:
public class Solution {
public int Fibonacci(int n) {
if(n == 0){
return 0;
}
if(n==1 || n==2 ){
return 1;
}
return Fibonacci(n-1)+Fibonacci(n-2);
}
}
非递归:
public class Solution {
public int Fibonacci(int n) {
if(n == 0){
return 0;
}
if(n==1 || n==2 ){
return 1;
}
int first= 1;
int second= 1;
int third= 0;
for(int i = 3;i< =n;i++){
third = first + second;
first = second;
second = third;
}
return third;
}
}