LCS最长公共子序列


1#include <iostream> 2 using namespace std; 3 4 void ProduceLcs(int m, int n, string **b, const string &str1) 5 { 6 if(m == 0 || n == 0) 7 return; 8 if(b[m][n] == "lefttop") 9 { 10 ProduceLcs(m - 1, n - 1, b, str1); 11 cout << str1[m - 1];//注意打印的是str的第二位,所以要减1,因为m对应的是矩阵的行 12 }else if(b[m][n] == "left") 13 { 14 ProduceLcs(m, n - 1, b, str1); 15 }else 16 { 17 ProduceLcs(m - 1, n, b ,str1); 18 } 19 return; 20 } 21 22 23 int LcsLength(string str1, string str2) 24 { 25 int m = str1.size() + 1; 26 int n = str2.size() + 1; 27 int c[m][n]; 28 //方向数组 29 string **b = new string *[m]; 30 for(int i = 0; i < m; ++i) 31 { 32 b[i] = new string[n]; 33 } 34 for(int i = 0; i < m; ++i) 35 { 36 c[i][0] = 0; 37 } 38 for(int i = 0; i < n; ++i) 39 { 40 c[0][i] = 0; 41 } 42 for(int i = 1; i < m; ++i) 43 { 44 for(int j = 1; j < n; ++j) 45 { 46 if(str1[i - 1] == str2[j -1]) 47 { 48 c[i][j] = c[i - 1][j - 1] + 1; 49 b[i][j] = "lefttop"; //左上 50 }else if(c[i - 1][j] >= c[i][j -1]) 51 { 52 c[i][j] = c[i - 1][j]; 53 b[i][j] = "top"; // 54 }else 55 { 56 c[i][j] = c[i][j - 1]; 57 b[i][j] = "left"; // 58 } 59 } 60 } 61 int len = 0; 62 for(int i = 0; i < m; ++i) 63 { 64 for(int j = 0; j < n; ++j) 65 { 66 if(c[i][j] > len) 67 { 68 len = c[i][j]; 69 } 70 } 71 } 72 ProduceLcs(m-1, n-1, b, str1); 73 cout << endl; 74 return len; 75 } 76 77 int main(int argc, const char *argv[]) 78 { 79 string str1 = "ABCBDAB"; 80 string str2 = "BDCABA"; 81 int max = LcsLength(str1, str2); 82 cout << max << endl; 83 return 0; 84 }

代码如上,注意在回溯求路径时候,打印的是对应的string里的字符,注意下标要减1。

posted @ 2015-04-08 20:04  bigshowxin  阅读(107)  评论(0编辑  收藏  举报