1143.最长公共子序列
体会一下本题和 718. 最长重复子数组 的区别
Python:
python
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
n, m = len(text1), len(text2)
dp = [[0]*(m+1) for _ in range(n+1)]
result = 0
for i in range(1, n+1):
for j in range(1, m+1):
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])
result = max(result, dp[i][j])
return result
C++:
cpp
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
vector<vector<int>> dp(text1.size()+1, vector<int>(text2.size()+1, 0));
int result = 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]);
}
result = max(result, dp[i][j]);
}
}
return result;
}
};
1035.不相交的线
其实本题和 1143.最长公共子序列 是一模一样的,大家尝试自己做一做。
Python:
python
class Solution:
def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
n, m = len(nums1), len(nums2)
dp = [[0]*(m+1) for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, m+1):
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[n][m]
C++:
cpp
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. 最大子序和
这道题我们用贪心做过,这次 再用dp来做一遍
Python:
python
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0]*len(nums)
dp[0] = nums[0]
result = nums[0]
for i in range(1, len(nums)):
dp[i] = max(dp[i-1]+nums[i], nums[i])
result = max(result, dp[i])
return result
C++:
cpp
class Solution {
public:
int maxSubArray(vector<int>& nums) {
vector<int> dp(nums.size(), 0);
dp[0] = nums[0];
int result = nums[0];
for (int i=1; i<nums.size(); i++) {
dp[i] = max(dp[i-1]+nums[i], nums[i]);
result = max(result, dp[i]);
}
return result;
}
};