Fibonacci number of DP beginner

Posted by kjb on Mon, 03 Jan 2022 05:14:18 +0100

509. Fibonacci number

Link to force buckle topic: https://leetcode-cn.com/problems/fibonacci-number

Fibonacci numbers are usually represented by F(n), and the sequence formed is called Fibonacci sequence. The sequence starts with 0 and 1, and each subsequent number is the sum of the first two numbers. That is: F(0) = 0, f (1) = 1, F(n) = f (n - 1) + F (n - 2), where n > 1 gives you n, please calculate F(n).

Example 1:

  • Input: 2
  • Output: 1
  • Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1

Example 2:

  • Input: 3
  • Output: 2
  • Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2

Example 3:

  • Input: 4
  • Output: 3
  • Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3

Tips:

  • 0 <= n <= 30

thinking

Fibonacci series should be very familiar to everyone. It is very suitable to practice as the first topic of dynamic rules.

Because this topic is relatively simple, some students may not need to do any analysis and write it directly.

But the style of "code Capriccio" is that simple questions are used to deepen the understanding of problem-solving methodology.

Through this topic, we can preliminarily realize how to solve the problem according to the dynamic rule trilogy.

For dynamic rules, if there is no methodology, maybe simple topics can be written easily, and if it is more difficult, I don't know how to start.

Therefore, the five dynamic planning trilogy I summarized is to run through the whole dynamic planning series, as mentioned earlier Recursive trilogy of binary tree seriesBacktracking trilogy of backtracking series Same. Later, we will slowly realize the importance of the five step method of dynamic regulation.

dynamic programming

Five parts of dynamic rules:

Here we will use a one-dimensional dp array to store the recursive results

  1. Determine the meaning of dp array and subscript

dp[i] is defined as: the Fibonacci value of the ith number is dp[i]

  1. Determine recurrence formula

Why is this a very simple introductory topic?

Because the topic has directly given us the recursive formula: state transition equation dp[i] = dp[i - 1] + dp[i - 2];

  1. How to initialize dp array

How to initialize is also directly given to us in the topic, as follows:

dp[0] = 0;
dp[1] = 1;
  1. Determine traversal order

From the recursive formula dp[i] = dp[i - 1] + dp[i - 2]; It can be seen that dp[i] depends on dp[i - 1] and dp[i - 2], so the traversal order must be from front to back

  1. Example derivation dp array

According to the recurrence formula dp[i] = dp[i - 1] + dp[i - 2], let's deduce that when N is 10, the dp array should be the following sequence:

0 1 1 2 3 5 8 13 21 34 55

If you write the code and find that the result is wrong, print out the dp array to see if it is consistent with the sequence we deduced.

We have finished the above analysis with the method of dynamic gauge, and the C + + code is as follows:

class Solution {
public:
    int fib(int N) {
        if (N <= 1) return N;
        vector<int> dp(N + 1);
        dp[0] = 0;
        dp[1] = 1;
        for (int i = 2; i <= N; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[N];
    }
};
  • Time complexity:
O(n)
  • Space complexity:
O(n)

Of course, we can find that we only need to maintain two values, and we don't need to record the whole sequence.

The code is as follows:

class Solution {
public:
    int fib(int N) {
        if (N <= 1) return N;
        int dp[2];
        dp[0] = 0;
        dp[1] = 1;
        for (int i = 2; i <= N; i++) {
            int sum = dp[0] + dp[1];
            dp[0] = dp[1];
            dp[1] = sum;
        }
        return dp[1];
    }
};
  • Time complexity:
O(n)
  • Space complexity:
O(1)

Recursive solution

This problem can also be solved by recursive method

The code is as follows:

class Solution {
public:
    int fib(int N) {
        if (N < 2) return N;
        return fib(N - 1) + fib(N - 2);
    }
};
  • Time complexity:
O(2^n)
  • Space complexity:
O(n)

, the space occupied by the system stack to realize recursion in the programming language is calculated

The time complexity of recursion is known by drawing a tree. If you are not clear, you can read this article: talk about the time complexity of recursion algorithm through an interview question!

summary

Fibonacci sequence is a very basic topic. I will mention Fibonacci sequence many times in the later explanation of dynamic programming!

Here I strictly follow the dynamic programming, you should know this! To analyze this problem, some analysis steps may not be necessary for students to make it so complex. In fact, the code can be rolled out.

However, I would like to emphasize that simple questions are used to master the methodology. The dynamic planning five series will play an important role in the next dynamic planning explanation. Please look forward to it!

On the sauce, learn the algorithm step by step and recognize the "code Capriccio"!

Other language versions

Java

class Solution {
    public int fib(int n) {
        if (n < 2) return n;
        int a = 0, b = 1, c = 0;
        for (int i = 1; i < n; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
}
//Uncompressed version
class Solution {
    public int fib(int n) {
        if (n <= 1) return n;
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        for (int index = 2; index <= n; index++){
            dp[index] = dp[index - 1] + dp[index - 2];
        }
        return dp[n];
    }
}

Python

class Solution:
    def fib(self, n: int) -> int:
        if n < 2:
            return n
        a, b, c = 0, 1, 0
        for i in range(1, n):
            c = a + b
            a, b = b, c
        return c

# Recursive implementation
class Solution:
    def fib(self, n: int) -> int:
        if n < 2:
            return n
        return self.fib(n - 1) + self.fib(n - 2)

Go:

func fib(n int) int {
    if n < 2 {
        return n
    }
    a, b, c := 0, 1, 0
    for i := 1; i < n; i++ {
        c = a + b
        a, b = b, c
    }
        return c
}

Javascript

var fib = function(n) {
    let dp = [0, 1]
    for(let i = 2; i <= n; i++) {
        dp[i] = dp[i - 1] + dp[i - 2]
    }
    console.log(dp)
    return dp[n]
};