【算法刷题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;
    }
}

总结

暂无

相关推荐
点云SLAM4 分钟前
图论中邻接矩阵和邻接表详解
算法·图论·slam·邻接表·邻接矩阵·最大团·稠密图
啊董dong10 分钟前
课后作业-2025年11月23号作业
数据结构·c++·算法·深度优先·noi
星释15 分钟前
Rust 练习册 80:Grains与位运算
大数据·算法·rust
程序员潇潇42 分钟前
Jenkins 插件下载速度慢安装失败?这篇文章可能解决你头等难题!
运维·自动化测试·软件测试·功能测试·程序人生·职场和发展·jenkins
zzzsde1 小时前
【C++】C++11(1):右值引用和移动语义
开发语言·c++·算法
sheeta19984 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
gfdhy9 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
Warren9810 小时前
Python自动化测试全栈面试
服务器·网络·数据库·mysql·ubuntu·面试·职场和发展
百***060110 小时前
SpringMVC 请求参数接收
前端·javascript·算法