Lecture 19
Lecture 19
Agenda:
• LCS
• Edit distance
Reading:
1
Lecture 19: Dynamic Programming
Definitions: – Sequence/string:
dynamicprogramming is a sequence over the English alpha-
bet
– Base/letter/character
– Subsequence:
the given sequence with zero or more letters deleted
e.g., dog is a subsequence of dynamicprogramming
WARNing: bases appear in the same order, but not nec-
essarily consecutive
– Common subsequence
– LCS problem: given two sequences X = x1 x2 . . . xn and
Y = y1 y2 . . . ym , find a maximum-length common subse-
quence of them.
2
Lecture 19: Dynamic Programming
• Therefore,
Letting DP [n, m] to denote the length of an LCS of X and
Y , then it is equal to
LCS(x1 x2 . . . xn−1 , y1 y2 . . . ym ),
max length of LCS(x1 x2 . . . xn , y1 y2 . . . ym−1 ),
LCS(x1 x2 . . . xn−1 , y1 y2 . . . ym−1 ) + ‘x0n , if xn = ym
• Correctness
• Recurrence:
If i = 0 or j = 0 then clearly DP [i, j] = 0.
Else
DP [i − 1, j],
DP [i, j] = max DP [i, j − 1],
DP [i − 1, j − 1] + 1, if xi = yj
3
Lecture 19: Dynamic Programming
• Pseudocode
procedure dpLCS(X, Y )
n ← length[X]
m ← length[Y ]
for i ← 1 to m do
DP [i, 0] ← 0
for j ← 0 to n do
DP [0, j] ← 0
for i ← 1 to n do
for j ← 1 to m do
if xi = yj then
DP [i, j] ← DP [i − 1, j − 1] + 1
else if DP [i − 1, j] ≥ DP [i, j − 1] then
DP [i, j] ← DP [i − 1, j]
else
DP [i, j] ← DP [i, j − 1]
return DP [n, m]
4
Lecture 19: Edit Distance
Editing Sequences:
5
Lecture 19: Edit Distance
Edit Distance:
• Thus:
Edit[i − 1, j] + Cost[si , δ],
Edit[i, j] = min Edit[i, j − 1] + Cost[δ, tj ],
Edit[i − 1, j − 1] + Cost[si , tj ],
Pi Pj
• with Edit[i, 0] = k=1
Cost[sk , δ] and Edit[0, j] = k=1
Cost[δ, tj ].
6
Lecture 19: Dynamic Programming
Edit Distance:
• Pseudocode
n ← length[S]
m ← length[T ]
Edit[0, 0] ← 0
for i ← 1 to n do
Edit[i, 0] ← Edit[i − 1, 0] + Cost[S[i], δ]
for j ← 1 to n do
Edit[0, j] ← Edit[0, j − 1] + Cost[δ, T [j]]
for i ← 1 to n do
for j ← 1 to m do
Op1 ← Edit[i − 1, j] + Cost[S[i], δ]
Op2 ← Edit[i, j − 1] + Cost[δ, T [j]]
Op3 ← Edit[i − 1, j − 1] + Cost[S[i], T [j]]
Edit[i, j] = min{Op1, Op2, Op3}
return Edit[n, m]
7
Lecture 19: Edit Distance
LCS
edit distance