文章链接:代码随想录
题目链接:1143.最长公共子序列
思路:一维数组没法记录全之前地依赖值。二维倒序也不行,因为还要依赖这层前面更新完的元素(dp[i][j - 1]),倒序的话这层前面元素还没更新,也是一维数组行不通的原因。
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
vector<vector<int>> dp(text1.size() + 1, vector<int>(text2.size() + 1));
int result = 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]);
result = result > dp[i][j] ? result : dp[i][j];
}
}
return result;
}
};
文章链接:代码随想录
题目链接:1035.不相交的线
思路:和求最长公共子序列一样
class Solution {
public:
int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {
vector<vector<int>> dp(nums1.size() + 1, vector<int>(nums2.size() + 1));
int result = 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]);
result = result > dp[i][j] ? result : dp[i][j];
}
}
return result;
}
};
思路:贪心做过,这次用动规方法记录。
class Solution {
public:
int maxSubArray(vector<int>& nums) {
vector<int> dp(nums.size());
dp[0] = nums[0];
int result = dp[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;
}
};
第五十三天打卡,加油!!!