本文主要是介绍代码随想录Day53:最长公共子序列、不相交的线、最大子序和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最长公共子序列
class Solution {
public:int longestCommonSubsequence(string text1, string text2) {vector<vector<int>> dp(text1.size() + 1, vector<int>(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()];}
};
不相交的线
class Solution {
public:int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {vector<vector<int>> dp(nums1.size() + 1, vector<int>(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][j - 1], dp[i - 1][j]);}}}return dp[nums1.size()][nums2.size()];}
};
最大子序和
动规:
class Solution {
public:int maxSubArray(vector<int>& nums) {if(nums.size() == 0) return 0;vector<int> dp(nums.size(), 0);dp[0] = nums[0];int res = dp[0];for(int i = 1; i < nums.size(); i++){dp[i] = max(dp[i - 1] + nums[i], nums[i]);res = max(dp[i], res);}return res;}
};
贪心:
class Solution {
public:int maxSubArray(vector<int>& nums) {if(nums.size() == 0) return 0;int res = INT_MIN;int sum = 0;for(int i = 0; i < nums.size(); i++){sum += nums[i];if(sum > res) res = sum;if(sum < 0) sum = 0;}return res;}
};
这篇关于代码随想录Day53:最长公共子序列、不相交的线、最大子序和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!