最长公共子序列 LCS

来源:互联网 发布:基于大数据的用户画像 编辑:程序博客网 时间:2024/05/18 12:03

算法导论上的LCS算法,动态规划的代表性算法

实现了一下,只是简单地找到一个LCS,并未全部列举出


#include <iostream>#include <stack>using namespace std;enum direct{LEFT = 0, UP, LEFT_UP};void LCS(char *str1, char *str2){const int length1 = strlen(str1);const int length2 = strlen(str2);int **common = new int*[length1 + 1];for(int i = 0; i <= length1; ++i)common[i] = new int[length2 + 1];direct **directions = new direct*[length1 + 1];for(int i = 0; i <= length1; ++i)directions[i] = new direct[length2 + 1];for(int i = 0; i <= length1; ++i)common[i][0] = 0;for(int i = 0; i <= length2; ++i)common[0][i] = 0;for(int i = 1; i <= length1; ++i)for(int j = 1; j <= length2; ++j){if(str1[i - 1] == str2[j - 1]){common[i][j] = common[i - 1][j - 1] + 1;directions[i][j] = LEFT_UP;}else{if(common[i - 1][j] >= common[i][j - 1]){common[i][j] = common[i - 1][j];directions[i][j] = LEFT;}else{common[i][j] = common[i][j - 1];directions[i][j] = UP;}}}cout << "the longest common subsequence's size is: " << common[length1][length2] << '\n';stack<char> st;int l1 = length1;int l2 = length2;while(l1 > 0 && l2 > 0){if(directions[l1][l2] == LEFT_UP){st.push(str1[l1 - 1]);--l1;--l2;}else if(directions[l1][l2] == LEFT)--l1;else--l2;}cout << "one of the LCS is: ";while(!st.empty()){cout << st.top();st.pop();}cout << endl;}int main(){LCS("as222d211f", "as1d2f2");return 0;}