"Design and Analysis of Algorithms" - the longest common subsequence essays

1. Definitions

Sequences of a given sequence is the sequence of the several elements omitted in the sequence obtained. For example, the sequence Z = {B, C, D, B} is the sequence X = {A, B, C, B, D, A, B} of the sequence, the corresponding index is incremented sequence {2,3,5 , 7}.

Given two sequences X and Y, Z when the sub-sequence of the other of both X and Y is the sequence when said Z is a common subsequence of X and Y sequence.

For example, if X = {A, B, C, B, D, A, B}, Y = {B, D, C, A, B, A}, the sequence {B, C, A} is the X and Y a common subsequence, but it is not the longest common subsequence of X and Y. Sequence {B, C, B, A} is a common subsequence X and Y, and its length is 4, and it is the longest common subsequence of X and Y, X and Y are not as common sub-length of more than 4 sequence.

2. Solution

Dynamic programming can effectively solve this problem. Indeed the specific nature of optimal substructure of the longest common subsequence problem.

3. Nature

Longest common subsequence of two sequences contain the longest common subsequence prefix of the two sequences. Longest common subsequence problem because the nature of optimal substructure, so that you can use dynamic programming algorithm to solve.

In fact, the sequence set X = {x1, x2, ..., xm} and Y = {y1, y2, y3, ... yn} is the longest common subsequence Z = {z1, z2, z3 ,. .., zk}

Then we can come out

(1) If xm = yn, then zk = xm = yn, and Zk-1 is the longest common subsequence Xm-1 and Yn-1 is;

(2) If xm! = Yn, and zk! = Xm, then Z is the longest common subsequence xm-1 and Y.

(3) If xm! = Yn, and zk! = Yn, z is X and Yn-1 is the longest common subsequence.

4. Calculate the best value

Dynamic programming algorithm calculates the longest common subsequence length of the sequence X = {x1, x2, x3, .., xn} and Y = {y1, y2, y3, ... yn} as input. Two output array c and b. A Where c [i] [j] is stored in the length of the longest common subsequence xi and yj, the value of b [i] [j] is recorded by a number of problems which sub-solution obtained, most of the algorithm optimal value of the recording and c [m] [n] of them.

Snippet:

public static int lcsLength(char[] x,char[] y,int [][]b){


int m = x.length-1;
int n = y.length-1;
int[][]c = new int[m+1][n+1];
for(int  i =1;i<=m;i++)c[i][0] = 0;
for(int  i =1;i<=n;i++)c[0][i] = 0;
for(int i = 11;i<=m;i++)
for(int j = 1;j<=n;j++){
if(x[i] == y[j]){
c[i][j] = c[i-1][j-1]+1;
b[i][j] = 1;
}
else if(c[i-1][j]>=c[i][j-1]){
c[i][j] = c[i-1][j];
b[i][j] = 2;
}
else{
c[i][j] = c[i][j-1];
b[i][j] = 3;
}
}
return c[m][n];
}

 

   

Guess you like

Origin blog.csdn.net/qq_40903237/article/details/94595200