Defined:
Subsequence: Part of the original sequence, required to appear in the order of the original sequence, but does not require continuous
Problem Description:
Given two sequences of x=<x1,x2,..., xm> and Y=<y1,y2,..., Yn>, find the maximum length of x and y common sub-sequences
Solving:
Step One: Optimal substructure (describes one of the longest common subsequence LCS)
Definition: xi=<x1,x2,..., xi>,yi=<y1,y2,..., yi>
Assuming that z=<z1,z2,..., zk> as an LCS for X and Y, there are:
1) If Xm=yn, then Zk=xm=yn, and Zk-1 is an LCS of Xm-1 and Yn-1
2) If Xm!=yn, then if ZK!=XM, then Z is an LCS of Xm-1 and yn
If Zk!=yn, then Z is an LCS of X and Yn-1
Step two: Construct recursive solutions
Defined:
C[i,j] Length of an LCS for sequence Xi and Yi
Formula:
C[i,j]=0 if I=0 or J =0
c[i,j]=c[i-1,j-1]+1 if I,j>0 and Xi=yj
C[i,j]=max (C[i-1,j],c[i,j-1]) if i,j>0 and Xi!=yj
Step three: Identify overlapping sub-problems and the number of real sub-problems
Calculate c[i-1,j] and c[i,j-1] will calculate c[i-1,j-1]
As can be seen directly in the form of recursive solutions, the number of sub-problems is θ (MN)
Step Four: Algorithm design
The code is as follows:
intCALCLS (stringS1,stringS2) { string:: Size_type m=s1.size () +1; string:: Size_type n=s2.size () +1; inti,j; int**c=New int*[M]; for(i=0; i<m;i++) C[i]=New int[n]; for(i=1; i<m;i++) c[i][0]=0; for(j=0; j<n;j++) c[0][j]=0; for(i=1; i<m;i++) { for(j=1; j<n;j++) if(s1[i]==S2[j]) c[i][j]=c[i-1][j-1]+1; Else if(c[i-1][j]>=c[i][j-1]) C[i][j]=c[i-1][j]; ElseC[i][j]=c[i][j-1]; } returnc[m-1][n-1];}
Longest common sub-sequence LCS