Cover image for LeetCode Hot 100 P1143 Longest Common Subsequence

LeetCode Hot 100 P1143 Longest Common Subsequence


Timeline

Timeline

2026-03-21

init

Dynamic Programming

Problem:

This is a classic problem,dp[i][j]representstext1[0..=i]andtext2[0..=j]the length of the longest common subsequence, and the state transition equation is

  • When text1[i]==text2[j]text1[i] == text2[j]:
    • dp[i][j]=dp[i1][j1]+1 dp[i][j] = dp[i-1][j-1] + 1
  • otherwise:
    • dp[i][j]=max(dp[i1][j],dp[i][j1]) dp[i][j] = max(dp[i-1][j], dp[i][j-1])
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
#include <string>#include <vector>using std::string;using std::vector;class Solution {    public:        int longestCommonSubsequence(string text1, string text2)        {                int i, j, n1 = text1.size(), n2 = text2.size();                vector<vector<int> > dp(n1, vector<int>(n2, 0));                for (i = 0; i < n1; i++) {                        if (text1[i] == text2[0]) {                                while (i < n1)                                        dp[i++][0] = 1;                                break;                        }                }                for (j = 0; j < n2; j++) {                        if (text2[j] == text1[0]) {                                while (j < n2)                                        dp[0][j++] = 1;                                break;                        }                }                // dp[i][j] represents the length of the longest common subsequence of text1[0..=i] and text2[0..=j]                // dp[i][j] = dp[i-1][j-1] + 1 (text1[i] == text2[j])                // dp[i][j] = max(dp[i-1][j], dp[i][j-1])                for (i = 1; i < n1; i++) {                        for (j = 1; j < n2; j++) {                                if (text1[i] == text2[j])                                        dp[i][j] = dp[i - 1][j - 1] + 1;                                else                                        dp[i][j] = std::max(dp[i - 1][j], dp[i][j - 1]);                        }                }                return dp[n1 - 1][n2 - 1];        }};
Loading comments…