1143.最长公共子序列
题目链接:https://leetcode.cn/problems/longest-common-subsequence/
文档讲解:https://programmercarl.com/1143.%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1…
视频讲解:https://www.bilibili.com/video/BV1ye4y1L7CQ
最近忙论文,简单记录一下
代码
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
for (int i = 1 ; i <= text1.length() ; i++) {
char char1 = text1.charAt(i - 1);
for (int j = 1; j <= text2.length(); j++) {
char char2 = text2.charAt(j - 1);
if (char1 == char2) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[text1.length()][text2.length()];
}
}
分析:时间复杂度:O(n * m),其中 n 和 m 分别为 text1 和 text2 的长度。空间复杂度: O(n * m)。
1035.不相交的线
题目链接:https://leetcode.cn/problems/uncrossed-lines/
文档讲解:https://programmercarl.com/1035.%E4%B8%8D%E7%9B%B8%E4%BA%A4%E7%9A%84…
视频讲解:https://www.bilibili.com/video/BV1h84y1x7MP
和上一题是一个意思,只是说法不一样
代码
class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
int[][] dp = new int[nums1.length + 1][nums2.length + 1];
for (int i = 1 ; i <= nums1.length; i++) {
for (int j = 1; j <= nums2.length; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[nums1.length][nums2.length];
}
}
分析:时间复杂度:O(n * m),空间复杂度:O(n * m)。
53. 最大子序和
题目链接:https://leetcode.cn/problems/maximum-subarray/
文档讲解:https://programmercarl.com/0053.%E6%9C%80%E5%A4%A7%E5%AD%90%E5%BA%8F…
视频讲解:https://www.bilibili.com/video/BV19V4y1F7b5
代码
class Solution {
public int maxSubArray(int[] nums) {
if (nums.length == 0) return 0;
int res = nums[0];
int[] dp = new int[nums.length];
dp[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
res = res > dp[i] ? res : dp[i];
}
return res;
}
}
分析:时间复杂度:O(n),空间复杂度:O(n)。
392.判断子序列
题目链接:https://leetcode.cn/problems/is-subsequence/
文档讲解:https://programmercarl.com/0392.%E5%88%A4%E6%96%AD%E5%AD%90%E5%BA…
视频讲解:https://www.bilibili.com/video/BV1tv4y1B7ym/
代码
class Solution {
public boolean isSubsequence(String s, String t) {
int length1 = s.length();
int length2 = t.length();
int[][] dp = new int[length1+1][length2+1];
for(int i = 1; i <= length1; i++){
for(int j = 1; j <= length2; j++){
if(s.charAt(i-1) == t.charAt(j-1)) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = dp[i][j-1];
}
}
if (dp[length1][length2] == length1) return true;
else return false;
}
}
分析:时间复杂度:O(n * m),空间复杂度:O(n * m)。