以下是典型动态算法打印两序列最大公共子序列的方法,该方法只能打印一个最大公共子序列:
1 #include2 using std::cout; 3 using std::endl; 4 5 const int NUM1=30,NUM2=30; 6 char result[NUM1+1]; 7 int count=0; 8 int lcsLength(char x[], char y[], int b[][NUM2+1],int m,int n) 9 {10 int c[NUM1+1][NUM2+1];11 for (int i = 0; i<=m; i++) 12 c[i][0]=0;13 for (int i = 0; i<=n; i++ ) 14 c[0][i]=0;15 for (int i = 1; i <= m; i++) 16 {17 for (int j = 1; j <= n; j++) 18 {19 if (x[i - 1]==y[j - 1])20 {21 c[i][j]=c[i-1][j-1]+1; 22 b[i][j]=1;23 }24 else 25 if (c[i-1][j]>c[i][j-1]) 26 {27 c[i][j]=c[i-1][j]; 28 b[i][j]=2;29 }30 else 31 {32 c[i][j]=c[i][j-1]; 33 b[i][j]=3;34 }35 }36 }37 return c[m][n];38 }39 40 void lcs(int i,int j, char x[], int b[][NUM2+1] ) 41 {42 if (i ==0 || j==0) 43 return;44 45 if(b[i][j]== 1) 46 { 47 lcs(i-1, j-1, x, b);48 cout<
只考虑最终的最优解,而不输出所有最优解或许是动态算法的很大的缺点。就这个问题,下面是一个粗糙的打印两序列所有最大公共子序列的方法:
1 #include2 using std::cout; 3 using std::endl; 4 5 const int NUM1=30,NUM2=30; 6 char result[NUM1+1]; 7 int count=0; 8 int lcsLength(char x[], char y[], int b[][NUM2+1],int m,int n) 9 {10 int c[NUM1+1][NUM2+1];11 for (int i = 0; i<=m; i++) 12 c[i][0]=0;13 for (int i = 0; i<=n; i++ ) 14 c[0][i]=0;15 for (int i = 1; i <= m; i++) 16 {17 for (int j = 1; j <= n; j++) 18 {19 if (x[i - 1]==y[j - 1])20 {21 c[i][j]=c[i-1][j-1]+1; 22 b[i][j]=1;23 }24 else 25 if (c[i-1][j]>c[i][j-1]) 26 {27 c[i][j]=c[i-1][j]; 28 b[i][j]=2;29 }30 else 31 if(c[i-1][j]