Salta al contenuto
Note per Studenti Dynamic Programming - Paradigm and Memoization Report

Dynamic Programming - Paradigm and Memoization

In questa pagina 6

Divide and conquer is memoryless: every node of the call tree is expanded in full, even when a node with the same subinstance has already been solved elsewhere. If subinstances repeat, the cost can become exponential. Dynamic programming (DP) keeps a table of the solutions already computed and reuses them.

A first example: Fibonacci numbers

Define F0=F1=1F_0 = F_1 = 1 and Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2} for n>1n > 1, so the values are 1,1,2,3,5,8,13,21,…1, 1, 2, 3, 5, 8, 13, 21, \dots (here F0=1F_0 = 1; other texts with F0=0F_0 = 0 call this Fn−1F_{n-1}). The definition suggests a divide and conquer algorithm:

RFIB(n)
  if n = 0 or n = 1 then return 1
  return RFIB(n-1) + RFIB(n-2)

Cost of the recursive version

Counting additions between integers, the number T(n)T(n) satisfies

T(n)={0n=0,1T(n−1)+T(n−2)+1n>1T(n) = \begin{cases} 0 & n = 0, 1 \\ T(n-1) + T(n-2) + 1 & n > 1 \end{cases}

Exact value: T(n)=Fn−1T(n) = F_n - 1. By induction on nn. Base: T(0)=0=F0−1T(0) = 0 = F_0 - 1 and T(1)=0=F1−1T(1) = 0 = F_1 - 1. Step: for n>1n > 1,

T(n)=T(n−1)+T(n−2)+1=(Fn−1−1)+(Fn−2−1)+1=Fn−1.T(n) = T(n-1) + T(n-2) + 1 = (F_{n-1} - 1) + (F_{n-2} - 1) + 1 = F_n - 1.

The number of calls (nodes of the tree) is 2Fn−12F_n - 1: each addition is an internal node, and a full binary tree with Fn−1F_n - 1 internal nodes has FnF_n leaves.

Exponential lower bound by unrolling. TT is non-decreasing, so T(n)≥2T(n−2)+1T(n) \ge 2T(n-2) + 1. Unrolling ii times:

T(n)≥2i T(n−2i)+∑j=0i−12j=2i T(n−2i)+2i−1.T(n) \ge 2^i\, T(n-2i) + \sum_{j=0}^{i-1} 2^j = 2^i\, T(n-2i) + 2^i - 1.

The base cases are reached when n−2i∈{0,1}n - 2i \in \{0, 1\}, i.e. for i⋆=⌊n/2⌋i^\star = \lfloor n/2 \rfloor, where T=0T = 0. Hence

T(n)≥2⌊n/2⌋−1=Θ((2)n).T(n) \ge 2^{\lfloor n/2 \rfloor} - 1 = \Theta\big((\sqrt 2)^n\big).

The exact value grows like φn\varphi^n with φ=1+52≈1.618\varphi = \frac{1 + \sqrt 5}{2} \approx 1.618.

Where work is wasted

Call tree for n=5n = 5 (value returned next to each node):

F(5)=8
├─ F(4)=5
│  ├─ F(3)=3
│  │  ├─ F(2)=2
│  │  │  ├─ F(1)=1
│  │  │  └─ F(0)=1
│  │  └─ F(1)=1
│  └─ F(2)=2
│     ├─ F(1)=1
│     └─ F(0)=1
└─ F(3)=3
   ├─ F(2)=2
   │  ├─ F(1)=1
   │  └─ F(0)=1
   └─ F(1)=1

There are 15=2F5−115 = 2F_5 - 1 calls and 7=F5−17 = F_5 - 1 additions. The subtree of F(3)F(3) is expanded twice, that of F(2)F(2) three times; the replication grows exponentially with nn.

Bottom-up: ITFIB

Fill a table F[0..n]F[0..n] from the base cases upwards.

ITFIB(n)
  if n = 0 or n = 1 then return 1
  F[0] <- 1
  F[1] <- 1
  for i <- 2 to n do
    F[i] <- F[i-1] + F[i-2]
  return F[n]
  • Correctness by induction on ii: F[0],F[1]F[0], F[1] are correct; if F[i−1]F[i-1] and F[i−2]F[i-2] are correct, so is F[i]F[i].
  • Cost: the loop runs n−1n - 1 times with one addition each: T(n)=n−1=Θ(n)T(n) = n - 1 = \Theta(n). For n=5n = 5: 44 additions against 77; for n=40n = 40: 3939 against F40−1=165 580 140F_{40} - 1 = 165\,580\,140.
ii 0 1 2 3 4 5 6 7
F[i]F[i] 1 1 2 3 5 8 13 21

Remark (instance size). Even Θ(n)\Theta(n) is inefficient with respect to the true size of the instance. The size of nn is the number of digits needed to write it, size(n)=Θ(log⁡n)\text{size}(n) = \Theta(\log n), so ITFIB is exponential in the size and RFIB doubly exponential. Algorithms with Θ(log⁡n)\Theta(\log n) arithmetic operations exist: since

(1110)n=(FnFn−1Fn−1Fn−2)\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^{n} = \begin{pmatrix} F_n & F_{n-1} \\ F_{n-1} & F_{n-2} \end{pmatrix}

(with F−1=0F_{-1} = 0), raising the 2×22 \times 2 matrix to the power nn by repeated squaring needs only Θ(log⁡n)\Theta(\log n) matrix products.

What dynamic programming is

DP keeps the idea of divide and conquer (a substructure property: the solution of an instance is obtained from solutions of smaller instances) but changes how things are computed. The process is purely bottom-up: start from the smallest instances and, combining stored solutions, reach the larger ones. The top-down phase of D&C (descending from the root to decide which subinstances are needed) disappears.

Conditions for DP to pay off:

  1. the problem has a substructure property;
  2. the generated subinstances appear several times (overlapping subproblems): this justifies the table;
  3. the space of subinstances is small (polynomial), because all of them are computed and stored.

Memoization

MemoizationFrom Latin memo, a reminder: not to be confused with memorization is a hybrid approach: keep the recursion of the substructure (hence the top-down phase of D&C) but use a global table, shared by all calls, where solved instances are saved. There are two procedures.

  1. INIT_X, non-recursive: solves the base cases, initializes the table (base cases plus a default value, the sentinel, for instances still to solve) and calls REC_X on the main instance.
  2. REC_X, recursive: checks whether the table already holds the solution; if so, returns it; otherwise computes it with Divide, Recurse, Conquer and stores it before returning.

For Fibonacci:

INIT_FIB(n)
  if n <= 1 then return 1
  F[0] <- 1
  F[1] <- 1
  for i <- 2 to n do F[i] <- 0       { 0 = not yet computed }
  return REC_FIB(n)

REC_FIB(i)
  if F[i] = 0 then F[i] <- REC_FIB(i-1) + REC_FIB(i-2)
  return F[i]

00 is a good default because no FiF_i is 00. The choice of sentinel is part of correctness: it must be a value the recurrence can never produce (−1-1 for lengths, +∞+\infty for minimum costs).

Call tree for n=5n = 5 (in execution order):

REC(5)
├─ REC(4)
│  ├─ REC(3)
│  │  ├─ REC(2)
│  │  │  ├─ REC(1)     base
│  │  │  └─ REC(0)     base      F[2] = 2
│  │  └─ REC(1)        base      F[3] = 3
│  └─ REC(2)           read from table      F[4] = 5
└─ REC(3)              read from table      F[5] = 8

Complexity analysis

The recurrence cannot be used to evaluate the cost: a recurrence describes the purely functional D&C execution, in which every node is expanded. One analyzes the tree. For Fibonacci the tree of REC_FIB(n) contains all instances of size less than nn, and each non-base instance i∈{2,…,n}i \in \{2, \dots, n\} appears as an internal node exactly once (all other occurrences are table reads). Therefore:

  • n−1n - 1 internal nodes with unit work (one addition);
  • the tree is a full binary tree, so nn leaves with no work;
  • T(n)=n−1T(n) = n - 1 additions and 2n−12n - 1 calls (for n=5n = 5: 44 additions, 99 calls).
pure D&C bottom-up memoized
table no yes yes
top-down phase yes no yes
subinstances solved every occurrence all in the space only those reached from the main instance
computation order automatic to be designed automatic
Fibonacci, additions Fn−1F_n - 1 n−1n - 1 n−1n - 1

Memoization is used less often, since bottom-up is usually just as efficient without recursion costs. It pays off when top-down avoids many subinstances (e.g. LCS of similar strings, see Longest Common Subsequencethe longest common subsequence of X (m symbols) and Y (n symbols) is found by dynamic programming on pairs of prefixes with l(i,j) = 0 if i = 0 or j = 0, 1 + l(i-1,j-1) if x_i = y_j, max of the two neighbours otherwise; bottom-up costs mn comparisons, reconstruction O(m+n), pure divide and conquer costs C(m+n,m) - 1 internal nodes, and space drops to Theta(min{m,n}) if only the length is needed.Longest Common Subsequence →) or when the bottom-up order is hard to write. In Python it is one line:

python
from functools import cache

@cache
def fib(n):
    return 1 if n <= 1 else fib(n - 1) + fib(n - 2)

assert [fib(i) for i in range(8)] == [1, 1, 2, 3, 5, 8, 13, 21]

Optimization problems and optimal substructure

A computational problem Π⊆I×S\Pi \subseteq I \times S relates instances to solutions; the feasible solutions of i∈Ii \in I are S(i)={s∈S:i Π s}S(i) = \{s \in S : i \,\Pi\, s\}. An optimization problem has a cost function c:S→Rc : S \to \mathbb{R} and asks for the best feasible solution (minimum or maximum of cc over S(i)S(i)). A solution s∗s^* is optimal if c(s∗)=min⁡/max⁡{c(s):s∈S(i)}c(s^*) = \min / \max \{c(s) : s \in S(i)\}.

Definition (optimal substructure). An optimization problem has optimal substructure if an optimal solution of an instance is obtained from optimal solutions of smaller instances.

It is almost always proved by cut-and-paste: assume by contradiction that a subsolution inside the optimal solution is not optimal, replace it with an optimal subsolution of the same subinstance, and obtain a strictly better overall solution, contradicting optimality.

Being an optimization problem does not imply that DP is needed: divide and conquer or the greedy approach (see Greedy Paradigm and Activity Selectionthe greedy paradigm makes the locally best choice immediately, cleans up the instance and solves the single residual subinstance (tail recursion, hence a loop); the code is easy and correctness is not, requiring the greedy choice property and optimal substructure; case study activity selection with the earliest-finish rule, full proof, Theta(n) after sorting, and counterexamples for wrong greedy rules.Greedy Paradigm and Activity Selection →) may also solve it. The choice depends on repeated subinstances (which make D&C inefficient) and on the size of the subproblem space (which must fit in a table).

The scheme of the paradigm

DP scheme.

  1. Optimal substructure. A relation between the optimal solution s∗s^* of an instance of size n>n0n > n_0 and the optimal solutions s1∗,…,sk∗s_1^*, \dots, s_k^* of strictly smaller instances, plus the base cases (size ≤n0\le n_0). It is proved (usually by cut-and-paste). Repeated subinstances justify DP.
  2. Cost. A recurrence on costs c(s∗)=f(c(s1∗),…,c(sk∗))c(s^*) = f\big(c(s_1^*), \dots, c(s_k^*)\big). 2'. Additional information. The minimum information needed to rebuild s∗s^* from s1∗,…,sk∗s_1^*, \dots, s_k^*.
  3. Cost computation, bottom-up (fill order consistent with the dependencies of the recurrence) or top-down memoized. 3'. Computation of the additional information, together with the costs.

Steps 2′2' and 3′3' are skipped if only the cost of the optimum matters, not the solution. If the solution is needed, whole subsolutions are not stored (too costly), only the incremental information: an arrow, or a split index. The optimal solution is then rebuilt in a postprocessing phase.

The three case studies below all follow this scheme:

problem subinstances how many choices per cell additional information order
Longest Common Subsequencethe longest common subsequence of X (m symbols) and Y (n symbols) is found by dynamic programming on pairs of prefixes with l(i,j) = 0 if i = 0 or j = 0, 1 + l(i-1,j-1) if x_i = y_j, max of the two neighbours otherwise; bottom-up costs mn comparisons, reconstruction O(m+n), pure divide and conquer costs C(m+n,m) - 1 internal nodes, and space drops to Theta(min{m,n}) if only the length is needed.Longest Common Subsequence → pairs of prefixes Θ(mn)\Theta(mn) 33 (arrow) arrow by rows or columns
Matrix Chain Multiplicationgiven the dimension vector p of a chain of n compatible matrices, find the parenthesization minimizing scalar products; parenthesizations are Catalan numbers (exponential), the subtrees of the last product are optimal (cut-and-paste), c(i,j) = min over k of c(i,k) + c(k+1,j) + p_(i-1) p_k p_j, divide and conquer costs 3^(n-1) - 1, bottom-up by increasing diagonals costs (n^3 - n)/3 products, and memoization never saves anything.Matrix Chain Multiplication → subchains Ai…AjA_i \dots A_j Θ(n2)\Theta(n^2) up to n−1n - 1 (index kk) index kk by increasing diagonals
String Alignment and Longest Palindromic Subsequencetwo string problems solved by dynamic programming like the LCS; optimal DNA alignment with score matrix S and gap penalty g uses C(i,j) = max{C(i-1,j-1) + s, C(i-1,j) + g, C(i,j-1) + g} in Theta(mn) time and Theta(min{m,n}) space for the cost alone, while the longest palindromic subsequence works on substrings with p(i,j) = 2 + p(i+1,j-1) if x_i = x_j, else max of the two shorter substrings, scanned by diagonals with n(n-1)/2 comparisons.String Alignment and Longest Palindromic Subsequence → pairs of prefixes; substrings Θ(mn)\Theta(mn); Θ(n2)\Theta(n^2) 33 arrow as LCS; by diagonals

For a worked exercise on counting operations of memoized code see Memoization of Triangular Recurrencesfor the recurrence M(i,j) = M(i+1,j-1) M(i+1,j) M(i,j-1) on the triangle 1 <= i <= j <= n, standard memoized code performs exactly (n-1)(n-2) multiplications, but all entries on a diagonal are equal, which cuts the work to 2(n-2) multiplications; look for regularities before filling a table.Memoization of Triangular Recurrences →.

Typical exam questions

  1. How many additions do RFIB(6) and ITFIB(6) perform? Answer: T(n)=Fn−1T(n) = F_n - 1 with F6=13F_6 = 13, so 1212 additions (and 2525 calls); ITFIB does n−1=5n - 1 = 5.
  2. Which conditions make DP convenient over D&C? Answer: optimal substructure; repeated subinstances; polynomial subproblem space.
  3. Why is the cost of a memoized algorithm not given by the D&C recurrence? Answer: the recurrence counts every node, but in the memoized tree many nodes are table reads; count internal nodes (n−1n - 1 for REC_FIB).

Versione ripasso

  • Fibonacci. F0=F1=1F_0 = F_1 = 1, Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}. RFIB: T(n)=T(n−1)+T(n−2)+1T(n) = T(n-1) + T(n-2) + 1, exactly T(n)=Fn−1T(n) = F_n - 1 (induction); calls 2Fn−12F_n - 1 (1515 for n=5n = 5, additions 77). Unrolling: T(n)≥2iT(n−2i)+2i−1T(n) \ge 2^i T(n-2i) + 2^i - 1 with i⋆=⌊n/2⌋i^\star = \lfloor n/2 \rfloor, so T(n)≥2⌊n/2⌋−1=Θ((2)n)T(n) \ge 2^{\lfloor n/2 \rfloor} - 1 = \Theta((\sqrt 2)^n); exact growth Θ(φn)\Theta(\varphi^n). Subtree of F(3)F(3) expanded twice, of F(2)F(2) three times.
  • ITFIB (table F[0..n]F[0..n], for i <- 2 to n): n−1n - 1 additions, correct by induction on ii. Size of nn is Θ(log⁡n)\Theta(\log n), so ITFIB is exponential in the size; (1110)n=(FnFn−1Fn−1Fn−2)\begin{pmatrix} 1 & 1 \\ 1 & 0 \end{pmatrix}^n = \begin{pmatrix} F_n & F_{n-1} \\ F_{n-1} & F_{n-2} \end{pmatrix} gives Θ(log⁡n)\Theta(\log n) operations.
  • DP conditions: substructure; overlapping subinstances; small (polynomial) subproblem space. Bottom-up: no top-down phase (pro: iterative; cons: solves useless subinstances, order to be designed).
  • Memoization = recursion + global table. INIT (base cases, table, sentinel, calls REC); REC (if in table return, else compute, store, return). The sentinel must never be a possible value (00 for Fibonacci, −1-1 for lengths, +∞+\infty for minima). Cost: count the tree, not the recurrence: n−1n - 1 internal nodes, nn leaves, 2n−12n - 1 calls (99 for n=5n = 5). Useful when top-down skips many subinstances or the order is hard.
ITFIB(n): F[0] <- F[1] <- 1; for i <- 2 to n do F[i] <- F[i-1] + F[i-2]; return F[n]
INIT_FIB(n): F[0] <- F[1] <- 1; for i <- 2 to n do F[i] <- 0; return REC_FIB(n)
REC_FIB(i):  if F[i] = 0 then F[i] <- REC_FIB(i-1) + REC_FIB(i-2); return F[i]
  • Optimization. S(i)S(i) feasible solutions, cost cc; optimal substructure = optimum contains optima of subinstances, proved by cut-and-paste. DP is not forced: D&C or greedy may work.
  • Scheme: (1) optimal substructure and base cases, (2) cost recurrence, (2') minimal additional information (arrow, index), (3) bottom-up or memoized computation, (3') information computed with the costs, then rebuild in postprocessing. If only the cost is needed skip 2′2' and 3′3'.
  • Comparison (Fibonacci): pure D&C Fn−1F_n - 1 additions; bottom-up n−1n - 1 (all subinstances, order designed); memoized n−1n - 1 (only reached subinstances, automatic order).
  • Applied to: LCS (prefix pairs, Θ(mn)\Theta(mn), 3 choices, arrow), Matrix Chain (subchains, Θ(n2)\Theta(n^2), up to n−1n - 1 choices, index kk, diagonals), alignment and palindromes.
  • Typical mistakes: analyzing the memoized code with the D&C recurrence; a sentinel that can be a real value; storing whole subsolutions instead of an arrow; forgetting F0=1F_0 = 1 here; calling ITFIB "linear" without distinguishing nn from its size.

Teoria collegata