【算法刷题day53】Leetcode:1143. 最长公共子序列、1035. 不相交的线、53. 最大子数组和

文章目录

草稿图网站
java的Deque

Leetcode 1143. 最长公共子序列

题目: 1143. 最长公共子序列
解析: **代码随想录解析**(https://programmercarl.com/1143.最长公共子序列.html

解题思路

和上一题的区别是,不初始化0,如果没匹配到就变为左边数

代码

java 复制代码
class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int res = 0;
        int [][]dp = new int[text1.length()+1][text2.length()+1];
        for (int i = 1; i <= text1.length(); i++) {
            for (int j = 1; j <= text2.length(); j++) {
                if (text1.charAt(i-1) == text2.charAt(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;
    }
}

//滚动数组
class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int res = 0;
        int []dp = new int[text2.length()+1];
        for (int i = 1; i <= text1.length(); i++) {
            for (int j = text2.length(); j > 0; j--) {
                if (text1.charAt(i-1) == text2.charAt(j-1))
                    dp[j] = dp[j-1] + 1;
                else
                    dp[j] = Math.max(dp[j], dp[j-1]);
                res = Math.max(res, dp[j]);
            }
        }
        return res;
    }
}

总结

暂无

Leetcode 1035. 不相交的线

题目: 1035. 不相交的线
解析: 代码随想录解析

解题思路

上秒那题包了个马甲

代码

java 复制代码
class Solution {
    public int maxUncrossedLines(int[] nums1, int[] nums2) {
        int res = 0;
        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]);
                res = Math.max(res, dp[i][j]);
            }
        }
        return res;
    }
}

总结

暂无

Leetcode 53. 最大子数组和

题目: 53. 最大子数组和
解析: 代码随想录解析

解题思路

dp数组的含义是到这位置的最大和是多少

代码

java 复制代码
class Solution {
    public int maxSubArray(int[] nums) {
        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(nums[i], nums[i] + dp[i-1]);
            res = Math.max(res, dp[i]);
        }
        return res;
    }
}

总结

暂无

相关推荐
Jack207 小时前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树8 小时前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2121 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2121 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术1 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦1 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
用户497863050731 天前
(一)小红的数组操作
算法·编程语言
怕浪猫2 天前
Electron 系列文章封面图
算法·架构·前端框架
徐小夕2 天前
JitWord 3.0 正式发布,高精度Word异构解析+复杂组件兼容,打造web端协同Word编辑器
前端·vue.js·算法