题解 | #最长公共子序列(一)#
最长公共子序列(一)
https://www.nowcoder.com/practice/672ab5e541c64e4b9d11f66011059498
动态规划板子 #include<iostream> #include<vector> #include<algorithm> using namespace std; int dp[1002][1002]; int main() { int n, m; char s1[1001]; char s2[1001]; scanf("%d%d", &n, &m); scanf("%s%s", s1 + 1, s2 + 1); // dp[i][j] s1的前i个元素 s2的前j个元素 的最大公共长度 for (int j = 0; j <= m; ++j) { dp[0][j] = 0; } for (int i = 0; i <= n; i++) { dp[i][0] = 0; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { // s1[1]- s1[i] 和 s2[1]-s2[j] if (s1[i] == s2[j]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); } } } cout << dp[n][m] << endl; return 0; }