๐ DP Fundamentals
You're calculating Fibonacci numbers. The naive recursive approach recalculates the same values over and over. Dynamic Programming remembers previous results, making it incredibly efficient! This is the power of DP - solving problems by remembering answers to subproblems.
What is Dynamic Programming?
Dynamic Programming Definition
Dynamic Programming (DP) is an optimization technique that solves complex problems by:
- Breaking them into smaller subproblems
- Solving each subproblem only once
- Storing results to avoid recomputation
Key properties:
- โ Overlapping Subproblems: Same subproblem solved multiple times
- โ Optimal Substructure: Optimal solution contains optimal subproblem solutions
Two Approaches: Memoization vs Tabulation
DP can be implemented two ways:
Memoization (Top-Down)
- Recursive approach with caching
- Think: "How do I solve this using subproblems?"
- Only solves needed subproblems
- Uses recursion stack
Tabulation (Bottom-Up)
- Iterative approach building from base cases
- Think: "Build from smallest to largest"
- Solves all subproblems
- No recursion (more control)
See the Comparison
Classic Example: Fibonacci
Fibonacci is the perfect DP example - it has overlapping subproblems!
Fibonacci Problem
Recurrence: F(n) = F(n-1) + F(n-2)
Base cases: F(0) = 0, F(1) = 1
Naive recursion: O(2^n) - recalculates same values!
DP solution: O(n) - each value calculated once
The Complete Code
Click Run to execute your code
Climbing Stairs Problem
Climbing stairs is essentially Fibonacci in disguise!
Problem
You can climb 1 or 2 steps at a time. How many ways to reach step n?
Solution: dp[i] = ways to reach step i
Recurrence: dp[i] = dp[i-1] + dp[i-2] (same as Fibonacci!)
When to Use Each Approach
Use Memoization When:
- Natural recursive thinking fits the problem
- Not all subproblems need to be solved
- Recursion depth is acceptable
Use Tabulation When:
- Need to avoid recursion stack overflow
- Want more control over computation order
- All subproblems will be needed anyway
Key DP Insights
DP Problem-Solving Checklist
- Recognize overlapping subproblems - Are you solving same thing multiple times?
- Define state - What does dp[i] or dp[i][j] represent?
- Find recurrence - How to compute dp[i] from previous states?
- Set base cases - What are the smallest subproblems?
- Choose approach - Memoization or tabulation?
Summary
What You've Learned
- DP Definition: Optimization by solving subproblems once
- Two Approaches: Memoization (top-down) and Tabulation (bottom-up)
- Key Properties: Overlapping subproblems + Optimal substructure
- Fibonacci: Classic DP example - O(2^n) โ O(n)
- Climbing Stairs: Fibonacci in disguise
- Both approaches: Same time complexity, different style
What's Next?
You've learned the fundamentals! Next, we'll explore 1D DP Problems - House Robber, Coin Change, and other single-array dynamic programming challenges!
Enjoying these tutorials?