【剑指Offer】10.1 斐波那契数列

题目描述

求斐波那契数列的第 n 项,n <= 39。
在这里插入图片描述

解题思路

考虑到第 i 项只与第 i-1 和第 i-2 项有关,因此只需要存储前两项的值就能求解第 i 项

public class Solution {
    public int Fibonacci(int n) {
// 1 1 2 3 5
        if(n <= 1)
            return n;
        
        int l = 0;
        int r = 1;
        int temp = 0;
        for(int count = 2; count <= n; count++) {
           	temp = l;
            l = r;
            r = temp + r;
        }
        return r;
    }
}

由于待求解的 n 小于 40,因此可以将前 40 项的结果先进行计算,之后就能以 O(1) 时间复杂度得到第 n 项的值。

public class Solution {
    private int[] temp = new int[40];
     
    public Solution() {
        temp[0] = 0;
        temp[1] = 1;
        for(int i = 2; i < temp.length; i++) {
            temp[i] = temp[i-1] + temp[i-2];
        }
    }
    
    public int Fibonacci(int n) {
// 1 1 2 3 5
        return temp[n];
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43469680/article/details/107834937