Leetcode Leetcode 509. Fibonacci Number

Topic:

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

Solution:

The problem is very simple. It
is to return a Fibonacci sequence.
Dynamic programming can be used. The
relationship is F(n) = F(n-1) + F(n-2).
Each value is equal to the sum of the first two.

Code:

class Solution:
    def fib(self, n: int) -> int:
        if n < 2:
            return n
        
        a, b = 0, 1

        for i in range(2, n + 1):
            a, b = b, a + b
        
        return b

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112411252