current position:Home>Common algorithm: Fibonacci sequence

Common algorithm: Fibonacci sequence

2022-01-26 22:24:14 Yan Long

subject :

Write a function , Input n , Fibonacci, please (Fibonacci) The number of the sequence n term ( namely F(N)). Fibonacci series is defined as follows : F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), among N > 1.

Answer key 1: recursive

class Solution {
public:

    map<int, int> cache;
    int fib(int n) {
        if (n == 0 || n == 1) {
            return n;
        }

        if (cache.find(n) != cache.end()) {
            return cache[n];
        }

        int res = (fib(n - 1) + fib(n - 2)) % 1000000007;
        cache[n] = res;

        return res;
    }
};

Answer key 2: belt dp Dynamic programming of memorandum

class Solution {
public:

    int fib(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        
       if(n == 2) {
            return 1;
        }

        vector<int> dp(n + 1, 0);
        // base case
        dp[1] = dp[2] = 1;
        for (int i = 3; i < n + 1; i++) {
            dp[i] = dp[i - 2] + dp[i - 1];
        }
        
        return dp[n];
    }
};

tips: 1、 When using recursion , You need to cache the results of the previous addition 2、 The addition result needs to be correct 1000000007 Remainder operation , Prevent the result from exploding .

copyright notice
author[Yan Long],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262224121181.html

Random recommended