Dynamic Programming
Common DP Problems¶
Knapsack Prolem¶
Rod Cutting Problem¶
Text Justification Problem¶
\(\text{cost} = \sum\limits_{\text{all lines}} (\text{extra space chars in line})^2\)
Supports distributing the extra spaces accross the lines larger spaces cost more than many small spaces
Inputs:
- A string of text
text
with \(n\) words of varying lengths - Each line must have a fixed width \(w\)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
\(DP[i]\) = min cost from word \(i\) Original Problem = \(DP[0]\)
Recurrance = \(DP[i] = min(line\_cost(i, j), DP[j]) \; \forall \; j \in \{i+1, i+2, ..., n\}\)
Bottom Up Approach¶
Order for solving DP can be determined using toposort.
1 2 3 4 5 6 7 8 9 |
|
Top Down Up Approach¶
Order for solving DP can be determined using toposort.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Matrix Chain Parenthesization Problem¶
Given \(n\) matrices \(M_1, ..., M_n\) such that the product \(\prod\limits_{i=1}^{n} M_i\) is well defined (\(M_i\) commutes with \(M_{i+1}\)) determine the minimum number of scalar multiplications needed to compute the product.
If \(AB\) where \(A\) is \(m \times n\) and \(B\) is \(n \times o\) then the multiplications needed is \(mno\)
If \(ABC\) where \(A\) is \(n \times 1\) where \(B\) is \(1 \times n\) and \(C\) is \(n \times 1\), computing \(A(BC)\) is faster than \((AB)C\)
So an order of optimum multiplication needs to be determined!
For \(\prod\limits_{i=1}^{n}M_i\) to be well defined, the dimesions be: \(p_0, p_1, ..., p_n\).
A martix \(M_i\) has dim \(p_{i-1} \times p_i\)
let \(c[i,j] = \text{min cost for} \prod\limits_{k=i}^{j}M_k\) computed over all possible paranthesizations
The original problem is therefore: \(c[1, n]\)
Recurrance: \(c[i, j] = min(c[i, k] + c[k+1, j] + p_{i-1}p_{k}p_{j}) \; \forall \; k \in \{i, i+1, ... j-1\}\) where \(i < j\)
Bottom Up Approach¶
1 2 3 4 5 6 7 8 9 10 |
|
Top Down Approach¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Longest Common Subsequence¶
Bottom Up Approach¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Top Down Approach¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
Bottom Up vs Top Down¶
If all sub problems must be solved once, BU is better because less initialisation and recursion overhead
If not all sub problems need to be solved though, top down approach is better because then we only solve those problems which require solving