状态表示:dp[i][j]长度为0-i-1的字符串t1与长度为0-j-1的字符串t2的最长公共子序列为dp[i][j]
方法:dp
class Solution {
#define maxn 1010
int dp[maxn][maxn];
public:
int longestCommonSubsequence(string text1, string text2) {
int n = text1.size(), m = text2.size();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (text1[i-1] == text2[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[n][m];
}
};
$时间复杂度O(n*m),空间复杂度O(n*m)
方法:dp
状态表示:dp[i][j]长度为0-i的字符串t1与长度为0-j的字符串t2的最长公共子序列为dp[i][j]
class Solution {
#define maxn 1010
int dp[maxn][maxn];
public:
int longestCommonSubsequence(string text1, string text2) {
int i, j;
int n = text1.size(), m = text2.size();
for(i = 0; i < n; ++i) {
for(j = 0; j < m; ++j) {
int same = (text1[i] == text2[j] ? 1 : 0);
if(i == 0 && j == 0) {
dp[i][j] = same;
}else if(i == 0) {
dp[i][j] = dp[i][j-1] || same;
}else if(j == 0) {
dp[i][j] = dp[i-1][j] || same;
}else if(same) {
dp[i][j] = dp[i-1][j-1] + 1;
}else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[n-1][m-1];
}
};
$时间复杂度O(n*m),空间复杂度O(n*m)
方法:dp
思路同上一题
class Solution {
#define maxn 1010
int dp[maxn][maxn];
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (nums1[i-1] == nums2[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[n][m];
}
};
$时间复杂度O(n*m),空间复杂度O(n*m)