题目描述
897.最长公共子序列
给定两个长度分别为 NN 和 MM 的字符串 AA 和 BB,求既是 AA 的子序列又是 BB 的子序列的字符串长度最长是多少。
样例
cin>>
4 5
acbd
abedc
cout<<
3
算法1
(dp) $O(n^2)$
首先所有dp都需要继承之前的dp,其次如果恰巧两个子序列相等的话,继承最大的那个+1就可以了。
时间复杂度
参考文献
C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
char a[N], b[N];
int n, m, dp[N][N];
int main(void){
cin >> n >> m >> a + 1 >> b + 1;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
if(a[i] == b[j]) dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
}
cout << dp[n][m] << endl;
return 0;
}