🖨️ Printing Instructions: Press Ctrl/Cmd + P and select "Save as PDF".
1

Dynamic Programming: Memoization & Tabulation

2

Learning Goals

3

What is Dynamic Programming?

4

Origins and Definition

5

Two Key Properties

6

DP vs Greedy vs Divide & Conquer

7

Example: Fibonacci

8

Interactive Demo: Recursion Tree

9

The Problem

10

Naive Recursive Fibonacci

Fib(n)
  if n <= 1 return n
  return Fib(n-1) + Fib(n-2)
11

Overlapping Subproblems

12

Memoization (Top-Down)

13

The Idea

14

Memoized Fibonacci

Map memo
Fib(n)
  if n in memo return memo[n]
  if n <= 1 f = n
  else f = Fib(n-1) + Fib(n-2)
  memo[n] = f
  return f
15

Tabulation (Bottom-Up)

16

Interactive Demo: DP Fibonacci

17

The Idea

18

Memoization vs Tabulation

19

Main Example: Rod Cutting

20

Interactive Demo: Rod Cutting

21

Problem Statement

22

Example Data

23

Recursive Formulation

24

Cut-Rod (Naive Recursive)

Cut-Rod(p, n)
  if n == 0 return 0
  q = -infinity
  for i = 1 to n
    q = max(q, p[i] + Cut-Rod(p, n-i))
  return q
25

Analysis of Naive Approach

26

DP Solution

27

Bottom-Up-Cut-Rod

let r[0..n] be new array
r[0] = 0
for j = 1 to n
  q = -infinity
  for i = 1 to j
    q = max(q, p[i] + r[j-i])
  r[j] = q
return r[n]
28

Complexity

29

Reconstructing the Solution

30

Finding the Actual Cuts

31

Extended-Bottom-Up-Cut-Rod

let r[0..n], s[0..n] be new arrays
r[0] = 0
for j = 1 to n
  q = -infinity
  for i = 1 to j
    if q < p[i] + r[j-i]
      q = p[i] + r[j-i]
      s[j] = i  // best first cut for size j
  r[j] = q
return r, s
32

Print-Cut-Rod-Solution

(r, s) = Extended-Bottom-Up-Cut-Rod(p, n)
while n > 0
  print s[n]
  n = n - s[n]
33

Subproblem Graphs

34

Visualizing Dependencies

35

The DP Design Recipe

36

4 Steps of DP

37

Recognizing DP Problems

38

Common Pitfalls

39

Watch Out For...

40

All Interactive Demos

41

Lecture Summary

42

Supplementary Resources