链接: 1143. 最长公共子序列
链接: 1035. 不相交的线
链接: 53. 最大子数组和
1143. 最长公共子序列
lass Solution {
public int longestCommonSubsequence(String text1, String text2) {
int len1 = text1.length(), len2 = text2.length();
int[][] dp = new int[len1 + 1][len2 + 1];
int res = 0;
for(int i = 1; i < len1 + 1; i++){
char c1 = text1.charAt(i-1);
for(int j = 1; j < len2 + 1; j++){
char c2 = text2.charAt(j-1);
if(c1 == c2){
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[len1][len2];
}
}
1035. 不相交的线
这一题和上一题一模一样
class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
if(nums1.length == 1 && nums2.length == 1 && nums1[0] != nums2[0]) return 0; // 剪枝
int len1 = nums1.length, len2 = nums2.length;
int[][] dp = new int[len1 + 1][len2 + 1];
int res = 0;
for(int i = 1; i < len1 + 1; i++){
for(int j = 1; j < len2 + 1; 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[len1][len2];
}
}
53. 最大子数组和
class Solution {
public int maxSubArray(int[] nums) {
if(nums.length == 1) return nums[0];
int[] dp = new int[nums.length];
int res = nums[0];
dp[0] = nums[0];
for(int i = 1; i < nums.length; i++){
dp[i] = Math.max(dp[i-1] + nums[i], nums[i]);
if(dp[i] > res) res = dp[i];
}
return res;
}
}