本文主要是介绍代码随想录训练营day44|动态规划part11,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最长公共子序列
力扣题目链接
class Solution {
public:int longestCommonSubsequence(string text1, string text2) {int len1 = text1.length();int len2 = text2.length();vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));for(int i = 1; i <= len1; i++){for(int j = 1; j <= len2; j++){if(text1[i-1] == text2[j-1]){dp[i][j] = max(dp[i-1][j-1]+1, max(dp[i-1][j], dp[i][j-1]));}else{dp[i][j] = max(dp[i-1][j], dp[i][j-1]);}}}return dp[len1][len2];}
};
不相交的线
力扣题目链接
class Solution {
public:int maxUncrossedLines(vector<int>& nums1, vector<int>& nums2) {int len1 = nums1.size();int len2 = nums2.size();vector<vector<int>> dp(len1+1, vector<int>(len2+1, 0));for(int i = 1; i <= len1; i++){for(int j = 1; j <= len2; 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[len1][len2];}
};
最大子序和
力扣题目链接
class Solution {
public:int maxSubArray(vector<int>& nums) {vector<int> dp(nums.size(), 0);int result = nums[0];dp[0] = nums[0];for(int i = 1; i < nums.size(); i++){dp[i] = max(dp[i-1], 0) + nums[i];result = max(result, dp[i]);}return result;}
};
判断子序列
力扣题目链接
class Solution {
public:bool isSubsequence(string s, string t) {int len1 = s.length();int len2 = t.length();vector<vector<bool>> dp(len1+1, vector<bool>(len2+1, false));for(int i = 0; i <= len2; i++){dp[0][i] = true;}for(int i = 1; i <= len1; i++){for(int j = i; j <= len2; j++){if(dp[i][j-1]){dp[i][j] = true;}else if(s[i-1] == t[j-1]){dp[i][j] = dp[i-1][j-1];}}}return dp[len1][len2];}
};
这篇关于代码随想录训练营day44|动态规划part11的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!