【重点】【DP】1143.最长公共子序列|516.最长回文子序列

两个求解代码类似的题目,对比记忆!!!

1143.最长公共子序列

题目

法1:DP,考虑空串

java 复制代码
class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length() + 1, n = text2.length() + 1; // 加1是在构建二维矩阵时增加空串情况, 简化计算
        int[][] dp = new int[m][n];
        for (int i = 1; i < m; ++i) {
            for (int j = 1; j < n; ++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][j - 1], dp[i - 1][j]);
                }
            }
        }


        return dp[m - 1][n - 1];
    }
}

法2:DP,不考虑空串

代码会啰嗦很多,所以还是法1好哇!!!

java 复制代码
class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length(), n = text2.length();
        int[][] dp = new int[m][n];
        boolean existed = false;
        for (int i = 0; i < n; ++i) {
            dp[0][i] = (existed || text1.charAt(0) == text2.charAt(i)) ? 1 : 0;
            if (dp[0][i] == 1) {
                existed = true;
            }
        }
        existed = false;
        for (int i = 0; i < m; ++i) {
            dp[i][0] = (existed || text1.charAt(i) == text2.charAt(0)) ? 1 : 0;
            if (dp[i][0] == 1) {
                existed = true;
            }
        }

        for (int i = 1; i < m; ++i) {
            for (int j = 1; j < n; ++j) {
                if (text1.charAt(i) == text2.charAt(j)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);
                }
            }
        }

        return dp[m - 1][n - 1];
    }
}

516.最长回文子序列

题目

java 复制代码
class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        for (int i = 0; i < n; ++i) {
            dp[i][i] = 1;
        }
        for (int i = n - 1; i >= 0; --i) {
            for (int j = i + 1; j < n; ++j) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = (j - i == 1 ? 0 : dp[i + 1][j - 1]) + 2;
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
                }
            }
        }

        return dp[0][n - 1];
    }
}
相关推荐
王老师青少年编程1 天前
背包DP第12课:多重背包DP应用案例实践1
c++·动态规划·dp·背包dp·多重背包·csp·信奥赛
leo03083 天前
Hugging Face多卡训练“假快”?一文讲透`per_device_train_batch_size`的“陷阱”
llm·dp·huggingface·ddp
王老师青少年编程8 天前
线性DP第12课:线性DP应用案例实践:数字三角形
c++·动态规划·dp·线性dp·csp·信奥赛·数字三角形
烛衔溟9 天前
C语言动态规划:最长公共子序列深度解析
c语言·数学建模·动态规划·算法优化·最长公共子序列·lcs
寅双木19 天前
自己配一台电脑——视频输出接口
dp·hdmi·dvi·vga·视频输出口·配电脑
大千AI助手1 个月前
差分隐私:机器学习和数据发布中的隐私守护神
人工智能·神经网络·机器学习·dp·隐私保护·差分隐私·大千ai助手
louisdlee.1 个月前
树状数组维护DP——前缀最大值
数据结构·c++·算法·dp
盼满天繁星1 个月前
题解:AT_agc015_e [AGC015E] Mr.Aoki Incubator
dp·数据结构优化 dp
christ_lrs2 个月前
sm2025 模拟赛23 (2025.10.18)
贪心·dp·dp优化·基环树·二维数点
christ_lrs2 个月前
sm2025 模拟赛12 (2025.10.7)
dp