問題描述:字符序列的子序列是指從給定字符序列中隨意地(不一定連續)去掉若干個字符(可能一個也不去掉)后所形成的字符序列。令給定的字符序列X=“x0,x1,…,xm-1”,序列Y=“y0,y1,…,yk-1”是X的子序列,存在X的一個嚴格遞增下標序列<i0,i1,…,ik-1>,使得對所有的j=0,1,…,k-1,有xij=yj。例如,X=“ABCBDAB”,Y=“BCDB”是X的一個子序列。
解決方法:
1、窮舉法:針對序列x中所有的子序列(共2^m個),在Y序列中尋列是否存在相同序列,並找出其中最大的序列。這種方法的時間復雜度為O(2^m*2^n)。
2、動態規划法:引進一個二維數組c[][],用c[i][j]記錄X[i]與Y[j] 的LCS 的長度,b[i][j]記錄c[i][j]是通過哪一個子問題的值求得的,以決定搜索的方向。可以通過以下公式來計算從c[i][j]的值。
復雜度分析:
時間復雜度:O(m*n);
空間復雜度:O(m*n);
代碼:
1 #include "stdafx.h" 2 #include <iostream> 3 #include <string> 4 #define MAXLEN 100 5 using namespace std; 6 7 void GetLCSLen(string str1, string str2,int m,int n,int c[][MAXLEN],int b[][MAXLEN]) 8 { 9 int i, j; 10 for (i = 0; i <= m; i++) 11 c[i][0] = 0; 12 for (j = 1; j <= n; j++) 13 c[0][j] = 0; 14 15 for (i = 1; i <= m; i++) 16 { 17 for (j = 1; j <= n; j++) 18 { 19 if (str1[i - 1] == str2[j - 1]) 20 { 21 c[i][j] = c[i - 1][j - 1] + 1; 22 b[i][j] = 0; 23 } 24 else 25 { 26 if (c[i - 1][j] >= c[i][j - 1]) 27 { 28 c[i][j] = c[i - 1][j]; 29 b[i][j] = 1; 30 } 31 else 32 { 33 c[i][j] = c[i][j - 1]; 34 b[i][j] = 2; 35 } 36 } 37 } 38 } 39 } 40 41 void PrintLCS(int b[][MAXLEN], string x, int i, int j) //遞歸回溯最長子序列 42 { 43 if (i == 0 || j == 0) 44 return; 45 if (b[i][j] == 0) 46 { 47 PrintLCS(b, x, i - 1, j - 1); 48 cout<<x[i-1]; 49 } 50 else if (b[i][j] == 1) 51 PrintLCS(b, x, i - 1, j); 52 else 53 PrintLCS(b, x, i, j - 1); 54 } 55 56 int _tmain(int argc, _TCHAR* argv[]) 57 { 58 string s1 = "ABCBDAB"; 59 string s2 = "BDCABA"; 60 int strlen1 = s1.size(); 61 int strlen2 = s2.size(); 62 int b[MAXLEN][MAXLEN]; 63 int c[MAXLEN][MAXLEN]; 64 GetLCSLen(s1,s2,strlen1,strlen2,c,b); 65 cout << c[strlen1][strlen2] << endl; //輸出最長子序列長度 66 PrintLCS(b,s1,strlen1,strlen2); 67 return 0; 68 }
運行結果:
參考資料:
1、http://blog.csdn.net/v_july_v/article/details/6695482
2、http://blog.csdn.net/yysdsyl/article/details/4226630