C++ longest common subsequence problem

#include <iostream>
#include <cstring>
using namespace std;

const int MAXN = 1005;
int dp[MAXN][MAXN];

int main()
{
    string s1, s2;
    cin >> s1 >> s2;
    int len1 = s1.length(), len2 = s2.length();

    memset(dp, 0, sizeof(dp)); // 初始化为0

    // 动态规划求解
    for (int i = 1; i <= len1; i++) {
        for (int j = 1; j <= len2; j++) {
            if (s1[i-1] == s2[j-1]) {
                dp[i][j] = dp[i-1][j-1] + 1;
            }
            else {
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        }
    }

    cout << dp[len1][len2] << endl; // 输出最长公共子序列的长度

    return 0;
}

        This code uses the idea of ​​dynamic programming to solve the longest common subsequence problem. dp[i][j] represents the length of the longest common subsequence between the first i characters of the s1 string and the first j characters of the s2 string. The state transition equation is:

​if (s1[i-1] == s2[j-1]) {
    dp[i][j] = dp[i-1][j-1] + 1;
}
else {
    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
}

        If s1[i-1] == s2[j-1], it means that s1[i-1] and s2[j-1] can be used as the last character of the longest common subsequence, at this time dp[i][ j] should be dp[i-1][j-1]+1; otherwise, s1[i-1] and s2[j-1] cannot be the last character of the longest common subsequence at the same time. At this time, dp[ i][j] should be the maximum value among dp[i-1][j] and dp[i][j-1]. Finally, dp[len1][len2] is the length of the longest common subsequence.

Guess you like

Origin blog.csdn.net/SYC20110120/article/details/134623709