Longest Common Subsequence: Difference between revisions
From Rice Wiki
(Created page with "= 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") |
No edit summary |
||
Line 5: | Line 5: | ||
= Approach: dynamic programming = | = Approach: dynamic programming = | ||
Consider | |||
==== Optimal Substructure ==== | |||
Consider <math>X = \langle x_1, x_2, \ldots, x_m \rangle</math> and | |||
<math>Y = \langle y_1, y_2, \ldots, y_n \rangle</math>, and | |||
let <math>Z = \langle z_1, z_2, \ldots, z_k \rangle</math> be an LCS of | |||
<math>X</math> and <math>Y</math>. | |||
If <math>x_m = y_n</math>, then <math>z_k = x_m = y_n</math> and | |||
<math>Z_{k-1}</math> is an LCS of <math>X_{m-1}</math> and | |||
<math>Y_{n-1}</math>. | |||
If <math>x_m \neq y_n</math> and <math>Z_k \neq x_m</math>, then | |||
<math>Z</math> is an LCS of <math>X_{m-1}</math> and | |||
<math>Y</math>. | |||
If <math>x_m \neq y_n</math> and <math>Z_k \neq y_n</math>, then | |||
<math>Z</math> is an LCS of <math>X</math> and | |||
<math>Y_{n-1}</math>. |
Revision as of 03:23, 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
Optimal Substructure
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 .