Easy
010Fibonacci Number
Return the nth Fibonacci number where F(0) = 0 and F(1) = 1.
EXAMPLES
Example 1
Input
{
"n": 4
}
Output
3FUNCTION SHAPE
n: int→intSOLUTION NOTE
This is the definition of DP! Once you have the recurrence relation and base cases, the code writes itself. The hard part is discovering the correct recurrence.
Reveal reference solution +
pythonREFERENCE
def fib(self, n: int) -> int:
@cache
def dp(n):
if n in [0, 1]: return n
return dp(n-1) + dp(n-2)
return dp(n)Time
O(n)Space
O(n)