leetcode 509. Fibonacci number

leetcode 509. Fibonacci number

Question stem

Fibonacci number, usually expressed by F(n), the sequence formed is called Fibonacci sequence. The number sequence starts with 0 and 1, and each number after it is the sum of the previous 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

Prompt:
0 <= n <= 30

answer

You can directly hit the table

class Solution {
    
    
public:
    int fib(int n) {
    
    
        vector<int> fib(31,0);
        fib[0] = 0;
        fib[1] = 1;
        for(int i = 2 ; i < 31 ; ++i){
    
    
            fib[i] = fib[i - 1] + fib[i - 2];
        }
        return fib[n];
    }
};

You can also use two variables to store adjacent two bits to save space

class Solution {
    
    
public:
    int fib(int n) {
    
    
        if(n < 2){
    
    
            return n;
        }
        int first = 0;
        int second = 1;
        for(int i = 1 ; i < n ; ++i){
    
    
            int temp = first;
            first = second;
            second = temp + second;
        }
        return second;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43662405/article/details/112209770