代码随想录算法训练营Day53 | 1143.最长公共子序列 1035.不相交的线 53. 最大子序和 动态规划
LeetCode 1143.最长公共子序列
题目链接:LeetCode 1143.最长公共子序列
思路:
三种情况得到dp[i][j]
class Solution {
public:int longestCommonSubsequence(string text1, string text2) {int m = text1.size();int n = text2.size();vector<vector<int>> dp(m+1, vector<int>(n+1));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]);}}return dp[m][n];}
};
注意 :
- 连续,判断i-1和j-1
LeetCode 1035.不相交的线
题目链接:LeetCode 1035.不相交的线
思路:
与上面等价
class Solution {
public:int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {int m = nums1.size();int n = nums2.size();vector<vector<int>> dp(m+1, vector<int>(n+1));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][j-1], dp[i-1][j]);}}return dp[m][n];}
};
LeetCode 53. 最大子序和 动态规划
题目链接:LeetCode 53. 最大子序和 动态规划
思路:
取极大值
class Solution {
public:int maxSubArray(vector<int>& nums) {int n = nums.size();vector<int> dp(n);dp[0] = nums[0];int result = dp[0];for(int i=1; i<n; i++){dp[i] = max(dp[i-1]+nums[i], nums[i]);result = max(result, dp[i]);}return result;}
};
注意 :
- 注意初始化dp[0] = nums[0]