Dynamic programming has the following properties
Longest common subsequence of letters in two strings of length $m$ and $n$. No necessarily coherent. There are $2^{n + m}$ permutations.
Example : ABC and ACB. Construct a table, let the left most column and the topmost row contain zeroes. Every time $x_i = y_j$, increase the value of the cell and add right-up arrow. Else we point arrows up or right to largest neighboring cell and adding the value. As follows.
A | B | C | ||
0 | 0 | 0 | 0 | |
A | 0 | 1↖ | 1← | 1← |
C | 0 | 1↑ | 1↑ | 2↖ |
B | 0 | 1↑ | 2↖ | 2↑ |
Now by following the arrows from the largest number we can obtain $A,C$
Theorem 15.1. Let $X = (x_1, x_2, ... , x_m)$ and $Y = (y_1, y_2 , ... , y_n)$ be sequences, and let $Z = (z_1, z_2 , ..., z_k)$ be any LCS of $X$ and $Y$.
*Observe that we have exhausted all cases: if $x_m \ne y_n$, then we have 2 OR 3. We proof the three as follows
Overlapping subproblems In order to find LCS of $X$ and $Y$ we may need to find LCS of $X$ and $Y_{n - 1}$ and LCS of $X_{m - 1}$ and $Y$, each of which contains the subsproblem of finding LCS of $X_{m - 1}$ and $Y_{n - 1}$. Formalized that is
The resulting running time has been reduced from exponential to polynomial. The alg. fills a table of size $m \cdot n$.
The algorithm requires $O(m \cdot n)$ space to operate. This can be reduced if no backtracking is required - that is if we only need the length of the LCS, not the LCS it self. In this case we can discard all but the two most recent rows.