1143.最长公共子序列
cpp
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int t1 = text1.size(), t2 = text2.size();
vector<vector<int>> dp(t1 + 1, vector<int>(t2 + 1, 0));
for (int i = 1; i <= t1; ++i) {
for (int j = 1; j <= t2; ++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[t1][t2];
}
};
1035.不相交的线
cpp
class Solution {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
int t1 = nums1.size(), t2 = nums2.size();
vector<vector<int>> dp(t1 + 1, vector<int>(t2 + 1, 0));
for (int i = 1; i <= t1; ++i) {
for (int j = 1; j <= t2; ++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[t1][t2];
}
};
53. 最大子序和
cpp
class Solution {
public:
int maxSubArray(vector<int>& nums) {
// dp[i]表示以已nums[i]为结尾的最大子数组和
// dp[i] = max(dp[i - 1] + nums[i], nums[i])
// 初始化为0, dp[0] = nums[0]
vector<int> dp(nums.size(), 0);
dp[0] = nums[0];
int result = nums[0];
for (int i = 1; i < nums.size(); ++i) {
dp[i] = max(dp[i - 1] + nums[i], nums[i]);
if (dp[i] > result) result = dp[i];
}
return result;
}
};
392.判断子序列
cpp
class Solution {
public:
bool isSubsequence(string s, string t) {
int n1 = s.size(), n2 = t.size();
vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, 0));
for (int i = 1; i <= n1; ++i) {
for (int j = 1; j <= n2; ++j) {
if (s[i - 1] == t[j - 1])
dp[i][j] = dp[i - 1][ j - 1] + 1;
else
dp[i][j] = dp[i][j - 1];
}
}
return dp[n1][n2] == n1;
}
};