题目大意:
题解:
最长公共子序列模板题,设\(dp[i][j]\)为字符串\(A[1...i]\)与字符串\(B[1...j]\)的最长公共子序列长度,则状态转移方程为:
\[dp[i][j] = max\{dp[i-1][j-1] + (A[i] == B[j]), dp[i-1][j], dp[i][j-1]\}
\]
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int len1 = text1.length(), len2 = text2.length();
vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1));
for (int i = 1; i <= len1; ++i) {
for (int j = 1; j <= len2; ++j) {
dp[i][j] = max(dp[i - 1][j - 1] + (text1[i - 1] == text2[j - 1]), max(dp[i - 1][j], dp[i][j - 1]));
}
}
return dp[len1][len2];
}
};