Longest Common Subsequence: Difference between revisions
From Rice Wiki
No edit summary |
No edit summary |
||
Line 5: | Line 5: | ||
= Approach: dynamic programming = | = Approach: dynamic programming = | ||
Consider <math>X = \langle x_1, x_2, \ldots, x_m \rangle</math> and | Consider <math>X = \langle x_1, x_2, \ldots, x_m \rangle</math> and | ||
Line 24: | Line 22: | ||
<math>Z</math> is an LCS of <math>X</math> and | <math>Z</math> is an LCS of <math>X</math> and | ||
<math>Y_{n-1}</math>. | <math>Y_{n-1}</math>. | ||
==== Subproblems ==== | |||
It is clear from the above that there are three subproblems to examine: | |||
# <math>LCS(X_{m-1}, Y_{n-1})</math> | |||
# <math>LCS(X_{m}, Y_{n-1})</math> | |||
# <math>LCS(X_{m-1}, Y_{n})</math> | |||
Let us have <math>c[i,j]</math> be the length of the LCS for | |||
<math>X_i</math> and <math>Y_j</math>. We have | |||
<math> | |||
c[i,j] = \begin{cases} | |||
0 & i = 0 and j = 0 \\ | |||
c[i-1, j-1] + 1 & x_i = y_i \\ | |||
max(c[i-1, j], c[i - 1, j]) & x_i \neq y_i | |||
\end{cases} | |||
</math> |
Revision as of 03:31, 4 March 2024
Problem description
A sequence Z is a subsequence of another sequence X if all the elements in Z also appear in order in X. Notably, the elements do not need to be consecutive.
In the longest-common-subsequence problem (LCS), we wish to find a maximum-length common subsequence of X and Y.
Approach: dynamic programming
Consider and , and let be an LCS of and .
If , then and is an LCS of and .
If and , then is an LCS of and .
If and , then is an LCS of and .
Subproblems
It is clear from the above that there are three subproblems to examine:
Let us have be the length of the LCS for and . We have