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

总结

暂无

相关推荐
卷福同学29 分钟前
【AI编程】AI+高德MCP不到10分钟搞定上海三日游
人工智能·算法·程序员
mit6.82431 分钟前
[Leetcode] 预处理 | 多叉树bfs | 格雷编码 | static_cast | 矩阵对角线
算法
皮卡蛋炒饭.1 小时前
数据结构—排序
数据结构·算法·排序算法
??tobenewyorker2 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
贝塔西塔2 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
众链网络2 小时前
AI进化论08:机器学习的崛起——数据和算法的“二人转”,AI“闷声发大财”
人工智能·算法·机器学习
3 小时前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
飒飒真编程4 小时前
C++类模板继承部分知识及测试代码
开发语言·c++·算法
GeminiGlory4 小时前
算法练习6-大数乘法(高精度乘法)
算法
熬了夜的程序员5 小时前
【华为机试】HJ61 放苹果
算法·华为·面试·golang