1143.最长公共子序列
- dp[i][j]: 表示以text1以i-1为结尾text2以j-1为结尾的最长公共子序列为dp[i][j]
- 递推公式:如果text1[i-1] == text2[j-1] 那么dp[i][j] = dp[i-1][j-1] + 1;
如果不相同的话,那么dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
// dp[i][j]: 表示以text1以i-1为结尾text2以j-1为结尾的最长公共子序列为dp[i][j]
vector<vector<int>> dp(text1.size() + 1, vector<int>(text2.size() + 1, 0));
// 递推公式 if(text1[i-1] == text2[j-1]) dp[i][j] = dp[i-1][j - 1] + 1;
// 初始化
// 遍历
for(int i = 1; i <= text1.size(); ++i) {
for(int j = 1; j <= text2.size(); ++j) {
if(text1[i-1] == text2[j-1]) dp[i][j] = dp[i-1][j - 1] + 1;
else dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
}
}
// for(auto vec : dp) {
// for(int val : vec) cout << val << " ";
// cout << endl;
// }
return dp[text1.size()][text2.size()];
}
};
392.判断子序列
class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.size() > t.size()) return false;
vector<vector<int>> dp(s.size() + 1, vector<int>(t.size() + 1, 0));
for(int i = 1; i <= s.size(); ++i) {
for(int j = 1; j <= t.size(); ++j) {
if(s[i-1] == t[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
return dp[s.size()][t.size()] == s.size();
}
};
标签:1143,vector,随想录,text2,text1,序列,dp,size
From: https://www.cnblogs.com/cscpp/p/18284857