Algorithm Combat 1: Dynamic Programming: Longest Common Subsequence Problem c++

The following is a sample code of a dynamic programming algorithm implemented in C++ to solve the longest subsequence problem (Longest Common Subsequence):

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int longestCommonSubsequence(string text1, string text2) {
    
    
    int m = text1.length();
    int n = text2.length();

    // 创建二维数组dp,并初始化为0
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

    for (int i = 1; i <= m; ++i) {
    
    
        for (int j = 1; j <= n; ++j) {
    
    
            if (text1[i - 1] == text2[j - 1]) {
    
    
                // 如果两个字符相等,则最长子序列长度加一
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
    
    
                // 否则取前一个状态的最大值
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }

    return dp[m][n];
}

int main() {
    
    
    string text1 = "abcde";
    string text2 = "ace";

    int result = longestCommonSubsequence(text1, text2);

    cout << "The length of the longest common subsequence is: " << result << endl;

    return 0;
}

The above code uses a two-dimensional array dpto record the length of the longest common subsequence. By traversing the string text1and text2, based on whether the current characters are equal, update dpthe value of the array. Finally returns dp[m][n]as the length of the longest common subsequence.

Please note that the above code only solves the length of the longest common subsequence problem. If you need to get the specific longest common subsequence itself (not just the length), some additional operations are required. Hope this example helps you!

Guess you like

Origin blog.csdn.net/weixin_42499608/article/details/131318979