Day 53 动态规划
1143. 最长公共子序列
cpp
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.size() + 1, n = text2.size() + 1;
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; 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]); // text1[0, i - 2]与text2[0, j - 1]的最长公共子序列 和 text1[0, i - 1]与text2[0, j - 2]的最长公共子序列,取最大的。
}
}
}
return dp[text1.size()][text2.size()];
}
};
1035. 不相交的线
仔细想想,好像就是求两个数组的最长公共子序列
cpp
class Solution {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
int m = nums1.size() + 1, n = nums2.size() + 1;
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 1; i < m; i++)
{
for (int j = 1; j < n; 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[nums1.size()][nums2.size()];
}
};
53. 最大子数组和
动态规划
cpp
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxVal = nums[0];
for (int i = 1; i < nums.size(); i++)
{
nums[i] = max(nums[i], nums[i] + nums[i - 1]);
if (maxVal < nums[i])
{
maxVal = nums[i];
}
}
return maxVal;
}
};
贪心算法
cpp
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int sum = 0, maxSum = INT_MIN;
for (int i = 0; i < nums.size(); i++)
{
if (sum < 0)
{
sum = nums[i];
}
else
{
sum += nums[i];
}
if (maxSum < sum)
{
maxSum = sum;
}
}
return maxSum;
}
};