@
目录动态规划
● 1143.最长公共子序列
● 1035.不相交的线
● 53. 最大子序和 动态规划
1143.最长公共子序列
法1:动态规划
int longestCommonSubsequence(string text1, string text2) {
vector<vector<int>>dp(text1.size() + 1, vector<int>(text2.size() + 1,0));
int ans = 0;
for (int i = 1; i <= text1.size(); ++i) {
for (int j = 1; j <= text2.size(); ++j) {
if (text1[i - 1] == text2[j - 1]) {//此处为何比较的是(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[text1.size()][text2.size()];
}
1035.不相交的线
1035.不相交的线
法1:动态规划
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 - 1][j], dp[i][j - 1]);
}
}
}
return dp[nums1.size()][nums2.size()];
}
53. 最大子序和 动态规划
法1:动态规划
int maxSubArray(vector<int>& nums) {
//动态规划
vector<int>dp(nums.size(),0);
dp[0] = nums[0];
int ans = dp[0];//INT_MIN
for (int i = 1; i < nums.size(); ++i) {
dp[i] = max(dp[i - 1] + nums[i], nums[i]);
if (ans < dp[i]) ans = dp[i];
}
return ans;
}
标签:size,14,nums,int,53,vector,动态,dp,刷题
From: https://www.cnblogs.com/asupersource-tech/p/17441866.html