Viewing the Thinking Mode of Using Space for Time from an Algorithmic Problem

Recently brushed a very good algorithm question:

写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下:

F(0) = 0,   F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。

答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fei-bo-na-qi-shu-lie-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Ever since, this is not easy, I easily wrote the following code:

class Solution {
    public int fib(int n) {
        if(n < 2){
            return n;
        }
        return (fib(n-1) + fib(n-2))%1000000007;
    }
}

 Leetcode prompts that it runs timeout. Let's take a chestnut, taking f(6) as an example:

Obviously, we performed a lot of repetitive calculations, which greatly increased the time complexity!

 optimization:

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

We define an array and use space to store the value of f(n), which avoids a lot of repeated calculations and greatly reduces the time complexity!

 

 

Guess you like

Origin blog.csdn.net/qq_36428821/article/details/112299362