|
int max = 0; // Max LCS length seen so far String ans; // The LCS pattern of the "max" length int LCS(String x, String y, int n, String s) { int sol1, sol2; /* -------------- Base case -------------- */ if ( x == "" OR y == "" ) { /* -------------------------------------------- We ended the search - check the length of s -------------------------------------------- */ if ( n >= max ) { max = n; ans = s; // Remember the best answer } 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, n+1, xn + s ); // The LCS being tried is "xn + s" and it has length (n+1) /* ------------------------------------------- Use the solution of the smaller problem(s) to solve the ORIGINAL problem -------------------------------------------- */ return( sol1 + 1 ); } if ( xn != ym ) { /* ------------------------------------- Solve smaller problem(s) ------------------------------------- */ sol1 = LCS( x - xn , y, n, s ); // The LCS being tried is "xn + s" and it has length (n+1) sol2 = LCS( x , y - ym, n, s ); // The LCS being tried is "xn + s" and it has length (n+1) /* ------------------------------------------- Use the solution of the smaller problem(s) to solve the ORIGINAL problem -------------------------------------------- */ if ( sol1 ≥ sol2 ) return( sol1 ); else return( sol2 ); } } |