提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
一、力扣1143.最长公共子序列
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int n1 = text1.length();
int n2 = text2.length();
int[][] dp = new int[n1+1][n2+1];
int res = 0;
for(int i = 1; i <= n1; i ++){
char ch1 = text1.charAt(i-1);
for(int j = 1; j <= n2; j ++){
char ch2 = text2.charAt(j-1);
if(ch1 == ch2){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
res = Math.max(res, dp[i][j]);
}
}
return res;
}
}
二、力扣1035.不相交的线
class Solution {
public int maxUncrossedLines(int[] nums1, int[] nums2) {
int n1 = nums1.length + 1;
int n2 = nums2.length +1;
int[][] dp = new int[n1][n2];
int res = 0;
for(int i = 1; i < n1; i ++){
for(int j = 1; j < n2; 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]);
}
res = Math.max(res, dp[i][j]);
}
}
return res;
}
}
三、力扣 53. 最大子序和 动态规划
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
int res = nums[0];
for(int i = 1; i < n; i ++){
dp[i] = Math.max(nums[i], dp[i-1] + nums[i]);
res = Math.max(res, dp[i]);
}
return res;
}
}
本文介绍了三个使用动态规划解决的力扣编程挑战:1143题是最长公共子序列,通过比较两个字符串的字符来构建最大长度的相同子串;1035题是不相交的线,涉及在直线上的点配对以最大化非交叉线的数量;53题是最大子序和,寻找数组中的连续子数组以获得最大和。
881

被折叠的 条评论
为什么被折叠?



