« previous | Monday, September 24, 2012 | next »
Longest Common Subsequence
Suppose you have a sequence of elements over a finite set .
A sequence over is called a subsequence of iff it can be obtained from by deleting elements.
Put differently, there exist indices such that for all
For example, is a subsequence of
Suppose is also a sequence over .
We call a common subsequence of and iff it is a subsequence of and a subsequence of
For example, is a common subsequence of and .
Given two sequences
and
over a set
, what is the longest common subsequence
between them?
Naïve Solution: Brute Force
There are subsequences of . We could check every one of them, filtering them by whether they are subsequences of (this would take time), and then determine the longest one. Overall, this takes time.
Dynamic Approach
If is a sequence, let be the th prefix of such that .
Let be the longest common subsequence between and .
Let and . Let .
- If , then certainly and is in .
- If , then implies that is in .
- If , then implies that is in .
(2) and (3) indicate overlapping subproblems of choosing the larger common subsequence of each of the two cases.
Recursive Solution
Let be the length of an element in .
Dynamic Programming Solution
Start our table by initializing the first row and column to 0 since the length of a common subsequence of [sequences of length 0] is 0.
Calculate for .
Calculate for . (etc.)
Return .
The complexity of computing this solution has been reduced to .
In computing , this particular solution depends on the cells directly above, to the right, and diagonally from it.
Whenever we satisfy case (1), choosing the diagonal solution, we know that we have grabbed the th element from the end of .
Keep track of the direction toward the optimal solution chosen (up, left, or diagonal)
To reconstruct the solution, start in and follow arrows, taking whenever has a "diagonal pointer".
Example
For sequences
|
|
B |
D |
C |
A
|
|
0 |
0 |
0 |
0 |
0
|
A
|
0 |
↑ 0 |
↑ 0 |
↑ 0 |
↖ 1
|
B
|
0 |
↖ 1 |
← 1 |
← 1 |
↑ 1
|
C
|
0 |
↑ 1 |
↑ 1 |
↖ 2 |
← 2
|
B
|
0 |
↑ 1 |
↑ 1 |
↑ 2 |
↑ 2
|
To construct the soluion, follow arrows and obtain "BC"