该问题的详细分析:http://www.7747.net/kf/201104/87379.html
#include <iostream> #include <cassert> using namespace std; //最长公共子序列问题的一个一般的算法、时间复杂度为O(mn)。 // directions of LCS generation enum DIRECTION {LEFT = 1, UP, LEFTUP}; void Print_LCS(int **lsc_direction, const char *str1, const char *str2, int rows, int cols); // Get the length of two strings' LCSs, and print one of the LCSs // Input: str1 - the first string // str2 - the second string // Output: the length of two strings' LCSs // 复杂度为:O(M*N) int LCS(const char *str1, const char *str2) { assert((NULL != str1) && (NULL != str2)); int len1 = strlen(str1); int len2 = strlen(str2); //存放子序列长度的2维数组 int **LCS_length; LCS_length = new int* [len1]; for(int i = 0; i < len1; i++) LCS_length[i] = new int[len2]; for (int i = 0; i < len1; i++) for (int j = 0; j < len2; j++) LCS_length[i][j] = 0; //存放移动方向的2维数组 int **LCS_direction; LCS_direction = new int* [len1]; for(int i = 0; i < len1; i++) LCS_direction[i] = new int[len2]; for (int i = 0; i < len1; i++) for (int j = 0; j < len2; j++) LCS_direction[i][j] = 0; for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { if ((0 == i) || (0 == j)) { if (str1[i] == str2[j]) { LCS_length[i][j] = 1; LCS_direction[i][j] = LEFTUP; } else LCS_length[i][j] = 0; } // a char of LCS is found, // it comes from the left up entry in the direction matrix else if (str1[i] == str2[j]) { LCS_length[i][j] = LCS_length[i-1][j-1] + 1; LCS_direction[i][j] = LEFTUP; } else { LCS_length[i][j] = max(LCS_length[i-1][j], LCS_length[i][j-1]); if(LCS_length[i-1][j] > LCS_length[i][j-1]) LCS_direction[i][j] = LEFT; // it comes from the left entry in the direction matrix else LCS_direction[i][j] = UP; // it comes from the up entry in the direction matrix } } } cout<<"one of the most length subsequence is:"<<endl; Print_LCS(LCS_direction, str1, str2, len1 - 1, len2 - 1);//调用下面的函数输出最长子序列 cout<<endl; return LCS_length[len1-1][len2-1]; //返回子序列的最大长度 } // Print a LCS for two strings // Input: LCS_direction - a 2d matrix which records the direction of LCS generation // pStr1 - the first string // pStr2 - the second string // row - the row index in the matrix LCS_direction // col - the column index in the matrix LCS_direction // 复杂度为O(M+N) void Print_LCS(int **lsc_direction, const char *str1, const char *str2, int rows, int cols) { assert((NULL != str1) && (NULL != str2)); int len1 = strlen(str1); int len2 = strlen(str2); if (!(rows < len1 && cols < len2)) return; if(rows <0 || cols < 0) return; if (LEFTUP == lsc_direction[rows][cols]) { Print_LCS(lsc_direction, str1, str2, rows - 1, cols - 1); cout<<str1[rows]<<" "; } else if (LEFT == lsc_direction[rows][cols]) Print_LCS(lsc_direction, str1, str2, rows - 1, cols); else Print_LCS(lsc_direction, str1, str2, rows, cols - 1); } int main() { const char *str1 = "ABCBDAB"; const char *str2 = "BDCABA"; int maxLength = LCS(str1, str2); cout<<"max sub sequence length is :"<<maxLength<<endl; system("pause"); }