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

总结

暂无

相关推荐
小超超爱学习993716 分钟前
大数乘法,超级简单模板
开发语言·c++·算法
Ricardo-Yang30 分钟前
SCNP语义分割边缘logits策略
数据结构·人工智能·python·深度学习·算法
凌波粒31 分钟前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展
啊哦呃咦唔鱼39 分钟前
LeetCode hot100-543 二叉树的直径
算法·leetcode·职场和发展
sinat_286945191 小时前
harness engineering
人工智能·算法·chatgpt
少许极端2 小时前
算法奇妙屋(四十三)-贪心算法学习之路10
学习·算法·贪心算法
算法鑫探2 小时前
10个数下标排序:最大值、最小值与平均值(下)
c语言·数据结构·算法·排序算法·新人首发
样例过了就是过了2 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
IronMurphy2 小时前
【算法三十七】51. N 皇后
算法·深度优先
DoUfp0bgq2 小时前
从直觉到算法:贝叶斯思维的技术底层与工程实现
算法