演算法學習之動態規劃--最長公共子序列
阿新 • • 發佈:2019-01-30
題目:
給出兩個字串,求出這樣的一個最長的公共子序列的長度:子序列中的每個字元都能在兩個原串中找到,而且每個字元的先後順序和原串中的先後順序一致。
Sample Input :
abcfbc abfcab
programming contest
abcd mnp
Sample Output :
4
2
0
題目分析:
輸入兩個串s1,s2, 設MaxLen(i,j)表示: s1的左邊i個字元形成的子串,與s2左邊的j個字元形成的子串的最長公共子序列的長度(i,j從0開始算),MaxLen(i,j) 就是本題的“狀態”
假定 len1 = strlen(s1), len2 = strlen(s2),那麼題目就是要求 MaxLen(len1,len2)
顯然有邊界值:
MaxLen(n,0) = 0 ( n= 0…len1)
MaxLen(0,n) = 0 ( n=0…len2)
遞推公式:
if ( s1[i-1] == s2[j-1] ) //s1的最左邊字元是s1[0]
MaxLen(i,j) = MaxLen(i-1,j-1) + 1;
else
MaxLen(i,j) = Max(MaxLen(i,j-1),MaxLen(i-1,j) );
時間複雜度O(mn) m,n是兩個字串長度
程式碼如下:
#include<iostream> #include<cstring> using namespace std; const int maxn = 1001; int maxLen[maxn][maxn]; char s1[maxn],s2[maxn]; int main(){ while(cin>>s1>>s2){ int len1 = strlen(s1), len2 = strlen(s2); for(int i=0; i<=len1; i++) //邊界條件賦值 maxLen[i][0] = 0; for(int j=0; j<=len2; j++) //邊界條件賦值 maxLen[0][j] = 0; for(int i=1; i<=len1; i++) for(int j=1; j<=len2; j++){ if(s1[i-1]==s2[j-1]) //狀態轉移方程 maxLen[i][j]=maxLen[i-1][j-1]+1; else maxLen[i][j]=max(maxLen[i-1][j],maxLen[i][j-1]); } cout<<maxLen[len1][len2]<<endl; } return 0; }