算法实战 1:动态规划:最长公共子序列问题 c++

以下是一个用C++实现的动态规划算法来解决最长子序列问题(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;
}

以上的代码使用了二维数组dp来记录最长公共子序列的长度。通过遍历字符串text1text2,根据当前字符是否相等,更新dp数组的值。最后返回dp[m][n]作为最长公共子序列的长度。

请注意,上述代码仅解决了最长公共子序列问题的长度,如果你需要获取具体的最长公共子序列本身(而不仅仅是长度),还需要进行某些额外的操作。希望这个示例能帮助到你!

猜你喜欢

转载自blog.csdn.net/weixin_42499608/article/details/131318979