





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






Outline
Last time:
Today:
Longest Common Subsequence (LCS)
Examples of LCS applications:
For string GDV EGT A, GV EA is an example subsequence of the string
Contrast:
the longest common subsequence is GV ET , note CET is also a common subsequence
Brute Force LCS
Given strings a and b, of length n and m respectively:
Dynamic Programming for LCS
Define L[i, j] = k to be the length of the LCS of
a[1,... , i] and b[1,... , j], where 1 ≤ i ≤ n and 1 ≤ j ≤ m
Question: Can we find overlapping subproblems such that the optimal
solution to the LCS problem consists of optimal solutions to the
subproblems?
Would the optimal solution for L[i, j] consists of optimal solutions for
L[i′, j′], where i′^ ≤ i and j′^ ≤ j?
Use similar approach to solving for the 0/1 Knapsack problem:
consider adding or not adding the last item to the solution of the
subproblem
DP for LCS
Let L[i, 0] = L[0, j] = 0, k the length of the LCS
Case 1: if a[i] 6 = b[j], one of them cannot be in the LCS of L[i, j], so either L[i, j] = L[i, j − 1] or L[i, j] = L[i − 1 , j] Since we want the longest common subsequence, L[i, j] = MAX(L[i, j − 1], L[i − 1 , j])
Case 2: if a[i] == b[j], then L[i − 1 , j − 1] must be k − 1
(Thus L[i, j] is optimal and consists of optimal solutions to the subproblems)
Proof by contradiction: assume L[i − 1 , j − 1] ≥ k, then adding a[i] to a[1,... , i − 1] and b[j] to b[1,... , j − 1] makes L[i, j] ≥ k + 1 ⇒ contradiction So:
L[i, j] =
0 if i = 0 or j = 0, L[i − 1 , j − 1] + 1 if i, j > 0 and a[i] == b[j], MAX(L[i − 1 , j], L[i, j − 1]) otherwise
(1)
LCS Extraction
Use stack to accummulate LCS in reversed order
Start from L[n, m]:
Alternative algorithm: again, start from L[n, m]:
Pop stack (if there are multiple common subsequences with the same length, each of the above extracts only one)