今天同事说他要离职啦,还挣挺多的,我也慢慢努力吧!!
儿子似乎有点斜颈,还好不是很大的病,儿子也开始面对人生的苦难啦。都好好加油生活!
1143.最长公共子序列
二维可以理解一点。
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
vector<vector<int>>dp(text1.size() + 1,vector(text2.size() + 1,0));
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-1][j],dp[i][j-1]);
}
}
}
return dp[text1.size()][text2.size()];
}
};
1035.不相交的线
其实就是和1143一模一样,只要顺序相同,就可以实现不相交。
class Solution {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
vector<vector<int>>dp(nums1.size() + 1,vector(nums2.size() + 1,0));
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-1][j],dp[i][j-1]);
}
}
}
return dp[nums1.size()][nums2.size()];
}
};
一维数组的思路很难其实,暂且放一下,先做下一题。
#include <iostream>
#include <string>
#include <vector>
using namespace ::std;
class Solution
{
public:
int longestCommonSubsequence(string text1, string text2)
{
// 首先要用text2的长度
vector<int> dp(text2.size() + 1, 0);
for (int i = 1; i <= text1.size(); i++)
{
int pre = dp[0];
for (int j = 1; j <= text2.size(); j++)
{
int cur = dp[j];
if (text1[i - 1] == text2[j - 1])
{
dp[j] = pre + 1;
}
else
{
dp[j] = max(dp[j], dp[j - 1]);
}
pre = cur;
}
cout << i << endl;
for (int j = 0; j <= text2.size(); j++)
{
cout << dp[j] << ' ';
}
cout << endl;
}
return dp[text2.size()];
}
};
int main()
{
Solution syz;
string text1 = "abcde";
string text2 = "ace";
syz.longestCommonSubsequence(text1, text2);
return 0;
}
//这里pre相当于dp[i - 1][j - 1]
结果如下,可以对齐二维的情况:
1
0 1 1 1
2
0 1 1 1
3
0 1 2 2
4
0 1 2 2
5
0 1 2 3
53. 最大子序和
和贪心思路很像。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
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(nums[i],dp[i-1]+nums[i]);
if(dp[i] > result)result = dp[i];
}
return result;
}
};