采用动态规划算法解决最长公共子序列问题
public class 最长公共子序列 {
public static void GET_LCS(int []X,int []Y){int m = X.length+1;
int n = Y.length+1;
int [][] b = new int[m][n];//存储路径
int [][] c = new int[m][n];//存储LCS值
for(int i = 0;i<m;i++){
c[i][0] = 0;
b[i][0] = 0;
}
for(int j = 0;j<n;j++){
c[0][j] = 0;
b[0][j] = 0;
}
LCS_LENGTH(X,Y,b,c,m,n);
PRINT_LCS(b,X,m-1,n-1);
for(int i = 0;i<m;i++){
for(int j = 0;j<n;j++){
System.out .print(b[i][j] + " ");
}
System.out .println(" ");
}
}
public static void LCS_LENGTH(int[] X,int []Y,int[][]b,int[][]c,int m,int n){
for(int i =1;i<m;i++){
for(int j = 1;j<n;j++){
if(X[i-1] == Y[j-1]){
c[i][j] = c[i-1][j-1] +1;
b[i][j] = 0;//0代表左上
}else if(c[i-1][j] >=c[i][j-1]){
c[i][j] = c[i-1][j];
b[i][j] = 1;//1代表上
}else{
c[i][j] = c[i][j-1];
b[i][j] = 2;//2代表左
}
}
}
}
public static int PRINT_LCS(int [][] b,int []X,int i,int j){
if(i==0||j==0){
return 0;
}
if(b[i][j] ==0){
PRINT_LCS(b,X,i-1,j-1);
System.out .println(X[i-1]);
}else if(b[i][j]==1){
PRINT_LCS(b,X,i-1,j);
}else{
PRINT_LCS(b,X,i,j-1);
}
return 0;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] X = {1,5,6,9,7,8,3,9};
int [] Y = {1,4,6,7,8,3};
GET_LCS(X,Y);
}
}