關於最長公共子序列(LCS)的相關知識,http://blog.csdn.net/liufeng_king/article/details/8500084 這篇文章講的比較好,在此暫時不再詳說。
以下是我程式碼實現兩種方式:遞迴+遞推:
1 #include <bits/stdc++.h> 2 using namespace std; 3 int A[100]; 4 int B[100]; 5 6 //int B[]={2,3,5,6,9,8,4}; 7 int d[100][100]={0}; 8 int dp(int i, int j,vector<int> &vs){ 9 int &ans = d[i][j]; 10 if(ans > 0)return ans; 11 if(i>0&&j>0){ 12 if(A[i] == B[j]){ 13 ans = dp(i-1,j-1)+1; 14 } 15 else ans = max(dp(i-1,j),dp(i,j-1)); 16 } 17 else{ 18 ans = 0; 19 } 20 return ans; 21 } 22 int LCS(int n1, int n2){ 23 for(int i = 0; i <= n1; i++)d[i][0] = 0; 24 for(int i = 0; i <= n2; i++)d[0][i] = 0; 25 for(int i = 1; i<= n1; i++){ 26 for(int j = 1; j<= n2; j++){ 27 if(A[i]==B[j]){ 28 d[i][j] = d[i-1][j-1]+1; 29 } 30 else d[i][j] = max(d[i-1][j], d[i][j-1]); 31 } 32 } 33 return d[n1][n2]; 34 } 35 int main(){ 36 int n1,n2 ; 37 cin >> n1; 38 for(int i = 1;i <= n1; i++) cin >> A[i]; 39 cin >> n2; 40 for(int i = 1;i <= n2; i++) cin >> B[i]; 41 memset(d,-1,sizeof(d)); 42 d[0][0] = 0; 43 vector<int> vs; 44 cout << dp(n1,n2,vs) << endl; 45 cout << LCS(n1 ,n2) << endl; 46 //cout << dp(5,6) << endl; 47 48 return 0; 49 }