动态规划
- 思路:
- 假设 dp[i][j] 是 text1[0:i] 和 text2[0:j] 最长公共子序列的长度;
- 则 dp[0][j] = 0,(空字符串和任何字符串的最长公共子序列的长度都是 0);
- 同理 dp[i][j] = 0;
- 状态转移方程:
- 当 text1[i - 1] = text2[j - 1] 时,dp[i][j] = dp[i - 1][j - 1] + 1;
- 否则 dp[i][j] 取 dp[i - 1][j]、dp[i][j - 1] 中值大的;
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.length();
int n = text2.length();
std::vector<std::vector<int>> dp(m + 1, std::vector<int>(n + 1));
for (int i = 1; i <= m; ++i) {
char c1 = text1.at(i - 1);
for (int j = 1; j <= n; ++j ) {
char c2 = text2.at(j - 1);
if (c1 == c2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
};
——————————————————————————————————