The longest common subsequence:
Given a sequence x={x1,x2,x3...xm}, another sequence Z={Z1,Z2,Z3...ZK} is called a subsequence of x when the following conditions exist, i.e. there is a strictly incrementing x subscript sequence <i1,i2...ik> for all j=1,2 ... K satisfies Xi=zj. Given two series X, Y, if both the X's subsequence and the Y subsequence, it is called the common sub-sequence of X. x and Y. The longest common subsequence is the longest or a few of all the subsequence sequences.
Solving the longest common subsequence problem with dynamic programming method:
1. Characterization of the longest common sub-sequence
Make X={X1,X2,X3...XM},Y={Y1,Y2,Y3...YN},Z={Z1,Z2,Z3...ZK} A common subsequence of x, Y.
The optimal sub-structure of LCS is:
1.if Xm==yn is Zk==xm==yn and Zk-1 is Xm-1,yn-1 's LCS
2. If xm! = yn then zk!=xm means z is xm-1 and Y's LCS
3.if xm! = yn so zk!=yn means z is x and yn-1 LCS
2. Recursive solutions
The definition c[i][j represents the XI and YJLCS lengths, with the following formula:
0 I==0 | | J==0
C[I][J] = c[i-1][j-1]+1 I,j>0&&xi==yj
Max (C[i][j-1], c[i-1][j]) I,j>0&&xi!=yj
3. Calculate the length of the LCS
Using b[i][j] to preserve the optimal solution of sub-problems
Pseudo code: (Introduction to Algorithms)
C[I][J] and bar B[I][J] Tracking
4. Structuring LCS
Pseudo code:
Implementation code:
PackageDp_lcs;/*** Longest common sub-sequence *@authorwxisme * @time 2015-10-22 pm 4:49:44*/ Public classSolve_lcs { Public Static Char[] x; Public Static Char[] y; Public Static int[] C;//C[i][j] represents Xi,yj's LCS Public Static int[] b;//Record optimal values /*** Calculate LCS*/ Public Static voidlcs_length () {intm = x.length+1; intn = y.length+1; C=New int[M][n]; b=New int[M][n]; for(inti=0; i<m; i++) c[i][0] = 0; for(intj=0; j<n; J + +) c[0][J] = 0; for(intI=1; i<m; i++) { for(intJ=1; j<n; J + +) { if(X[i-1] = = Y[j-1]) {C[i][j]= C[i-1][j-1] + 1; B[I][J]= 1;//Upper left } Else if(C[i-1][j] >= c[i][j-1]) {C[i][j]= C[i-1][j]; B[I][J]= 2;//on } Else{C[i][j]= C[i][j-1]; B[I][J]= 3;//left } } } } /*** Construction LCS *@paramI *@paramJ*/ Public Static voidPrint_lcs (intIintj) {if(I==0 | | j==0) return ; if(B[i][j] = = 1) {Print_lcs (i-1, J-1); System.out.print (X[i-1]); } Else if(B[i][j] = = 2) {Print_lcs (i-1, J); } Else{Print_lcs (i, J-1); } } }
Test data:
Public Static void Main (string[] args) { new Solve_lcs (); New Char []{' A ', ' B ', ' C ', ' B ', ' D ', ' A ', ' B '}; New Char []{' B ', ' D ', ' C ', ' A ', ' B ', ' A '}; Ret.lcs_length (); Ret.print_lcs (X.length, y.length); }
Results:
Bcba
Introduction to the reference algorithm third edition
Longest common sub-sequence problem