数据结构学习 Leetcode1143最长公共子序列

动态规划 最长公共子序列LCS

这是我在看动态规划学习的时候做的。

这是一篇LCS。LCS是两个数组进行比较。

题目:

思路:

我觉得这个总结挺好的:

求两个数组或者字符串的最长公共子序列问题,肯定是要用动态规划的。

首先,区分两个概念:子序列可以是不连续的;子数组(子字符串)需要是连续的;

另外,动态规划也是有套路的:单个数组或者字符串 要用动态规划时,可以把动态规划 dp[i] 定义为 nums[0:i] 中想要求的结果;当两个数组或者字符串 要用动态规划时,可以把动态规划定义成两维的 dp[i][j] ,其含义是在 A[0:i]B[0:j] 之间匹配得到的想要的结果。

状态: dp[i][j]:第一个串的前i位和第二个串的前j位中的最长公共子序列

转移方程:

复杂度计算:

时间复杂度:O(nm)

空间复杂度:O(nm)

代码:

cpp 复制代码
#include <string>
#include <vector>
#include <iostream>
//动态规划
// 最长公共子序列
//时间复杂度:O(n×m)
//空间复杂度:O(n×m)
class Solution {
public:
    int longestCommonSubsequence(std::string text1, std::string text2) {
        std::vector<std::vector<int>> dp(text1.size(), std::vector<int>(text2.size(), 0));
        for (int i = 0; i < text1.size(); ++i)
        {
            for (int j = 0; j < text2.size(); ++j)
            {
                if (text1[i] == text2[j])
                    dp[i][j] = (i > 0 && j > 0) ? dp[i - 1][j - 1] + 1 : 1;
                else
                {
                    int a_tmp = i > 0 ? dp[i - 1][j] : 0;
                    int b_tmp = j > 0 ? dp[i][j - 1] : 0;
                    dp[i][j] = std::max(a_tmp, b_tmp);
                }
                    
            }
        }
        return dp[text1.size() - 1][text2.size() - 1];
    }
};

void Test_solution1()
{
    std::string text1{ "abceda" };
    std::string text2{ "acea" };
    Solution solution;
    std::cout<<solution.longestCommonSubsequence(text1, text2);
}
相关推荐
西岸行者5 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
悠哉悠哉愿意5 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
别催小唐敲代码5 天前
嵌入式学习路线
学习
毛小茛6 天前
计算机系统概论——校验码
学习
babe小鑫6 天前
大专经济信息管理专业学习数据分析的必要性
学习·数据挖掘·数据分析
winfreedoms6 天前
ROS2知识大白话
笔记·学习·ros2
在这habit之下6 天前
Linux Virtual Server(LVS)学习总结
linux·学习·lvs
我想我不够好。6 天前
2026.2.25监控学习
学习
im_AMBER6 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
CodeJourney_J6 天前
从“Hello World“ 开始 C++
c语言·c++·学习