题目链接

牛客网

题目描述

求斐波那契数列的第 n 项,n <= 39。

解题思路

  • Java
public class Solution {
   
    public int Fibonacci(int n) {
   
        if (n<=1) return n;
        int[] ans = new int[n+1];
        ans[0] = 0;
        ans[1] = 1;
        for (int i=2;i<=n;i++) {
   
            ans[i] = ans[i-1]+ans[i-2];
        }
        return ans[n];
    }
}
public int Fibonacci(int n) {
   
    if (n <= 1)
        return n;
    int pre2 = 0, pre1 = 1;
    int fib = 0;
    for (int i = 2; i <= n; i++) {
   
        fib = pre2 + pre1;
        pre2 = pre1;
        pre1 = fib;
    }
    return fib;
}