509. Fibonacci Number

Easy

Problem:

Calculate the Fibonacci sequence numbers.

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

https://leetcode.com/problems/fibonacci-numberarrow-up-right

Solution:

Memoization

class Solution:
    dp = collections.defaultdict(int)

    def fib(self, n: int) -> int:
        if n <= 1:
            return n
        if self.dp[n]:
            return self.dp[n]
        
        self.dp[n] = self.fib(n - 1) + self.fib(n - 2)
        return self.dp[n]

Tabulation

Space efficiency: O(1)

Last updated