Dynamic Programming21 sections · 916 units
Open in Course

The Main Idea

Remember results

What if you stored the result of fib(3)fib(3) the first time you computed it? Then when you need fib(3)fib(3) again, you just look it up instead of recalculating. This simple idea (remembering results to avoid duplicate work) is the core of dynamic programming.

I still remember the first time I read about it. DP (dynamic programming) was like a magic word, but seriously, that's it! You trade space (storing results) for time (avoiding recalculation). Instead of O(2n)O(2^n) time, you compute each value once, giving you O(n)O(n) time. Three lines of code. That's all it takes.