最長公共子序列
題目連結:1143. 最長公共子序列 - 力扣(LeetCode)
思路:。
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()];
}
};
不相交的線
題目連結:1035. 不相交的線 - 力扣(LeetCode)
思路:本題等同於求相同子序列長度
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 - 1][j], dp[i][j - 1]);
}
}
}
return dp[nums1.size()][nums2.size()];
}
};
最大子序和 動態規劃
題目連結:53. 最大子陣列和 - 力扣(LeetCode)
思路:之前貪心做過了,這次用dp
class Solution {
public:
int maxSubArray(vector<int>& nums) {
vector<int> dp(nums.size()+1,0);
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(result<dp[i])result=dp[i];
}
return result;
}
};