剑指offer 07:斐波那契数列

时间:2020-12-03 05:28:48

题目描述

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

法一:

public class Solution {
public int Fibonacci(int n) {
int[] fib = new int[40];
fib[0] = 0;
fib[1] = 1;
for(int i = 2; i < 40; i++)
fib[i] = fib[i-1] + fib[i-2];
return fib[n];
}
}

法二:

public class Solution {
public int Fibonacci(int n) {
if(n == 0 || n == 1)
return n;
int fn1 = 0;
int fn2 = 1;
for(int i=2; i<=n; i++){
fn2 += fn1;
fn1 = fn2 - fn1;
}
return fn2;
}
}