代码随想录算法训练营day44
1.最长公共子序列
1.1 题目
. - 力扣(LeetCode)
1.2 题解
class Solution
{
public:
int longestCommonSubsequence(string text1, string text2)
{
//确定dp数组,dp[i][j]表示长度为i的text1与长度为j的text2的最长公共子序列的长度
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;
else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);*/
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]);
}
}
return dp[text1.size()][text2.size()];
}
};
2.不相交的线
2.1 题目
. - 力扣(LeetCode)
2.2 题解
class Solution {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2)
{
//确定dp数组,dp[i][j]表示长度为i的nums1与长度为j的nums2的最长公共子序列的长度
vector<vector<int>> dp(nums1.size()+1, vector<int>(nums2.size()+1, 0));
//确定递推逻辑
/*if (nums1[i - 1] == nums2[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 (int i = 1; i <= nums1.size(); i++)
{
for (int j = 1; j <= nums2.size(); j++)
{
if (nums1[i - 1] == nums2[j - 1])dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
return dp[nums1.size()][nums2.size()];
}
};
3.最大子序和
3.1 题目
. - 力扣(LeetCode)
3.2 题解
class Solution {
public:
int maxSubArray(vector<int>& nums)
{
//确定dp数组,dp[i]表示以nums[i]结尾的数组的连续子数组的最大和
vector<int> dp(nums.size(), 0);
//确定递推关系
//dp[i] = max(dp[i - 1] + nums[i],nums[i]);
//初始化
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]);
result = max(result, dp[i]);
}
return result;
}
};
4.判断子序列
4.1 题目
. - 力扣(LeetCode)
4.2 题解
class Solution {
public:
bool isSubsequence(string s, string t)
{
//确定dp数组,dp[i][j]表示,长度为i的s与长度为j的t的最大公共子序列的长度
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] = dp[i][j - 1];
}
}
int length= dp[s.size()][t.size()];
if (length == s.size())return true;
return false;
}
};