Unit - 4 Dynamic_Programming (Longest Common Subsequence)
Unit - 4 Dynamic_Programming (Longest Common Subsequence)
Chapter – 4
Dynamic Programming
1
Longest Common Subsequence (LCS)
A subsequence is a sequence that appears in the same relative
order, but not necessarily contiguous.
Given two sequences X and Y , we say that a sequence Z is a
common subsequence of X and Y if Z is a subsequence of both
X and Y .
“Our goal here is to find such longest Z, that is longest common
Subsequence”.
2
Optimal Substructure (Formula)
if(A[i]=B[j]) then
C[i,j]=C[i-1,j-1]+1
D[i,j]=
else if(C[i-1,j]>=C[i,j-1]) then
C[i,j]=C[i-1,j]
D[i,j]=
else
C[i,j]=C[i,j-1]
D[i,j]=
3
Example: Find LCS of given two strings using Dynamic
Programming.
X = < A, B, C, B, D, A, B>
Y = <B, D, C, A, B, A>
4
Step - 1
5
Step - 2
6
Step - 3
7
Step - 4
8
Example: Find LCS of given two strings using Dynamic Programming.
yj B D C A B A
xi 0 0 0 0 0 0 0
A 0 0 0 0 1 1 1
B 0 1 1 1 1 2 2
C 0 1 1 2 2 2 2
B 0 1 1 2 2 3 3 LCS = BCBA
D 0 1 2 2 2 3 3
A 0 1 2 2 3 3 4
B 0 1 2 2 3 4 4