Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 509 Fibonacci - Base Cases

Two starting points

Every recursive solution needs base cases to stop the recursion. For Fibonacci, there are two: fib(0)=0fib(0) = 0 and fib(1)=1fib(1) = 1. Why two instead of one? Because the recurrence relation (a formula that defines each term using previous terms) fib(n)=fib(n1)+fib(n2)fib(n) = fib(n-1) + fib(n-2) needs two previous values.

If you only defined fib(0)fib(0), then computing fib(2)fib(2) would require fib(1)fib(1), which isn't defined yet. These two base cases are enough for the entire sequence and let you build up from the bottom. With base cases set, how do you compute the rest? That's the recursive formula.