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 and for , so the values are (here ; other texts with call this ). 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 satisfies
Exact value: . By induction on . Base: and . Step: for ,
The number of calls (nodes of the tree) is : each addition is an internal node, and a full binary tree with internal nodes has leaves.
Exponential lower bound by unrolling. is non-decreasing, so . Unrolling times:
The base cases are reached when , i.e. for , where . Hence
The exact value grows like with .
Where work is wasted
Call tree for (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)=1There are calls and additions. The subtree of is expanded twice, that of three times; the replication grows exponentially with .
Bottom-up: ITFIB
Fill a table 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 : are correct; if and are correct, so is .
- Cost: the loop runs times with one addition each: . For : additions against ; for : against .
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | |
|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 |
Remark (instance size). Even is inefficient with respect to the true size of the instance. The size of is the number of digits needed to write it, , so ITFIB is exponential in the size and RFIB doubly exponential. Algorithms with arithmetic operations exist: since
(with ), raising the matrix to the power by repeated squaring needs only 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.
- Advantage: an iterative algorithm, faster in practice (no recursion overhead).
- Drawback 1: all smaller subinstances reachable through the substructure are solved, even those that matter little or not at all for the given instance.
- Drawback 2: the bottom-up order must be designed by hand and is sometimes not obvious (see 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 →).
Conditions for DP to pay off:
- the problem has a substructure property;
- the generated subinstances appear several times (overlapping subproblems): this justifies the table;
- 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.
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 callsREC_Xon the main instance.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]is a good default because no is . The choice of sentinel is part of correctness: it must be a value the recurrence can never produce ( for lengths, for minimum costs).
Call tree for (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] = 8Complexity 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 , and each non-base instance appears as an internal node exactly once (all other occurrences are table reads). Therefore:
- internal nodes with unit work (one addition);
- the tree is a full binary tree, so leaves with no work;
- additions and calls (for : additions, 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 |
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:
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 relates instances to solutions; the feasible solutions of are . An optimization problem has a cost function and asks for the best feasible solution (minimum or maximum of over ). A solution is optimal if .
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.
- Optimal substructure. A relation between the optimal solution of an instance of size and the optimal solutions of strictly smaller instances, plus the base cases (size ). It is proved (usually by cut-and-paste). Repeated subinstances justify DP.
- Cost. A recurrence on costs . 2'. Additional information. The minimum information needed to rebuild from .
- 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 and 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:
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
- How many additions do
RFIB(6)andITFIB(6)perform? Answer: with , so additions (and calls); ITFIB does . - Which conditions make DP convenient over D&C? Answer: optimal substructure; repeated subinstances; polynomial subproblem space.
- 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 ( for
REC_FIB).
Versione ripasso
- Fibonacci. , .
RFIB: , exactly (induction); calls ( for , additions ). Unrolling: with , so ; exact growth . Subtree of expanded twice, of three times. - ITFIB (table ,
for i <- 2 to n): additions, correct by induction on . Size of is , so ITFIB is exponential in the size; gives 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, callsREC);REC(if in table return, else compute, store, return). The sentinel must never be a possible value ( for Fibonacci, for lengths, for minima). Cost: count the tree, not the recurrence: internal nodes, leaves, calls ( for ). 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. feasible solutions, cost ; 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 and .
- Comparison (Fibonacci): pure D&C additions; bottom-up (all subinstances, order designed); memoized (only reached subinstances, automatic order).
- Applied to: LCS (prefix pairs, , 3 choices, arrow), Matrix Chain (subchains, , up to choices, index , 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 here; calling ITFIB "linear" without distinguishing from its size.