java实现:
public class 最长公共子序列 { public static void main(String[] args) { // TODO Auto-generated method stub char X[] = {'?','A','B','C','B','D','A','B'}; char Y[] = {'?','B','D','C','A','B','A'}; LCS_length(X, Y); } public static void LCS_length(char x[], char y[]) { int m = x.length-1; int n = y.length-1; int b[][] = new int[m+1][n+1]; //保存对应的c[i][j]所选择的子问题的最优解 int c[][] = new int[m+1][n+1]; //c[i][j] 保存前缀为x[i]和y[j]的最长公共子序列的长度 for(int i = 0; i<= n; i++) { c[i][0] = 0; } // 当某“前缀”长度为0 时,最长公共子序列为0 for(int j = 0; j <= n; j++) { c[0][j] = 0; } for(int i = 1; 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;//“1”表示选择左上角的子问题最优解 } else if(c[i-1][j] >= c[i][j-1]) { c[i][j] = c[i-1][j]; b[i][j] = 2; //“2”代表选择左侧的子问题的最优解 } else { c[i][j] = c[i][j-1]; b[i][j] = 3;//“3”代表选择上方子问题的最优解 } } } System.out.println(c[m][n]); print_LCS(b, x, m, n); } public static void print_LCS(int b[][], char x[], int i, int j) { if(i ==0 || j == 0) { return ; } if(b[i][j] == 1) { print_LCS(b, x, i-1, j-1); System.out.print(x[i]); } else if(b[i][j] == 2) { print_LCS(b, x, i-1, j); } else { print_LCS(b, x, i, j-1); } } }