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