Key Points
-
Definition:
- DP solves problems by breaking them into overlapping subproblems, storing solutions to avoid re-computation.
- Example (Fibonacci):
- Naive recursion recalculates
fib(3)multiple times forfib(5). - DP stores
fib(3)after the first computation.
- Naive recursion recalculates
-
Properties:
- Optimal substructure: Solution depends on solutions to smaller subproblems.
- Example:
fib(n) = fib(n-1) + fib(n-2).
- Example:
- Overlapping subproblems: Identical subproblems recur.
- Example:
fib(3)is needed for bothfib(4)andfib(5).
- Example:
- Optimal substructure: Solution depends on solutions to smaller subproblems.
-
Methods:
-
Naive Recursion:
- Exponential time (), hits recursion limit.
def fib(n): if n == 1 or n == 2: return 1 return fib(n-1) + fib(n-2) -
Memoization (Top-Down):
- Cache results to avoid recomputation. Time: .
def fib(n, memo={1: 1, 2: 1}): if n not in memo: memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n] -
Tabulation (Bottom-Up):
- Iterative, no recursion. Time: , Space: (can optimize to ).
def fib(n): if n == 1 or n == 2: return 1 bu = [0] * (n+1) bu[1], dp[2] = 1, 1 for i in range(3, n+1): bu[i] = bu[i-1] + bu[i-2] return bu[n]
-
Example: Fibonacci Sequence
- Recurrence:
- Walkthrough (n=5):
- Naive: 9 redundant calls (e.g.,
fib(2)computed 3 times). - DP (Memoization): 5 calls (no recomputation).
- Naive: 9 redundant calls (e.g.,
Presentation Order
-
Define DP (2 mins):
- “DP avoids redundant calculations by storing subproblem results. For
fib(5), overlapping calls tofib(3)are cached.” - Draw recursion tree for
fib(5)and highlight repeated calls.
- “DP avoids redundant calculations by storing subproblem results. For
-
Properties & Methods (1 min):
- “Optimal substructure means
fib(n)builds onfib(n-1)andfib(n-2). Overlapping subproblems make caching efficient.” - Show code snippets for all three methods side-by-side.
- “Optimal substructure means
-
Example Walkthrough (1 min):
- Tabulate
fib(5)step-by-step:dp = [0, 1, 1, 2, 3, 5] - “DP reduces time from exponential () to linear ().”
- Tabulate