Note:
|
X = BAB length(X) = 3 Y = BBAB length(Y) = 4 |
Graphically:
|
Answer:
|
X = BAC length(X) = 3 Y = ABCB length(Y) = 4 |
Graphically:
|
Answer:
|
Note:
|
|
if ( xn == yn ) { Solution of original problem = sol1 + 1; } else { if ( sol2 >= sol3 ) { Solution of original problem = sol2; } else { Solution of original problem = sol3; } } |
LCS(0, m) = 0, for all m = 0, 1, 2, ... LCS(n, 0) = 0, for all n = 0, 1, 2, ... |
int LCS( x, y ) { int sol1, sol2, sol3; /* -------------- Base case -------------- */ if ( x == "" OR y == "" ) { return(0); // LCS has 0 characters } /* --------------------------------------- Compare the last character in x and y --------------------------------------- */ n = x.length() - 1; m = y.length() - 1; if ( xn == ym ) { /* ------------------------------------- Solve smaller problem(s) ------------------------------------- */ sol1 = LCS( x - xn , y - ym ); /* ------------------------------------------- Use the solution of the smaller problem(s) to solve the ORIGINAL problem -------------------------------------------- */ return( sol1 + 1 ); } else // ( xn != ym ) { /* ------------------------------------- Solve smaller problem(s) ------------------------------------- */ sol2 = LCS( x - xn , y ); sol3 = LCS( x , y - ym); /* ------------------------------------------- Use the solution of the smaller problem(s) to solve the ORIGINAL problem -------------------------------------------- */ if ( sol2 ≥ sol3 ) return( sol2 ); else return( sol3 ); } |
/* ---------------------------------- Meaning of the input parameters x = x0 x1 x2 .... x(i-1) y = y0 y1 y2 .... y(j-1) ---------------------------------- */ int LCS( int i, int j, String x, String y ) { int sol1, sol2, sol3; /* ======================================== Base cases ======================================== */ if ( i == 0 || j == 0 ) { /* ------------------------------------------ One of the strings has 0 character => no match possible Longest common subsequence = 0 characters ------------------------------------------- */ return(0); } if ( x.charAt(i-1) == y.charAt(j-1) ) { sol1 = LCS(i-1, j-1, x, y); // Solve smaller problem return( sol1 + 1 ); // Use solution to solve orig. problem } else { sol2 = LCS(i-1, j, x, y); // Solve smaller problems sol3 = LCS(i, j-1, x, y); if ( sol2 >= sol3 ) // Use solution to solve orig. problems { return(sol2); } else { return(sol3); } } } |