알고리즘 전투 1: 동적 프로그래밍: 가장 긴 공통 하위 시퀀스 문제 c++

다음은 가장 긴 하위 시퀀스 문제(Longest Common Subsequence)를 해결하기 위해 C++로 구현된 동적 프로그래밍 알고리즘의 샘플 코드입니다.

#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;
}

위의 코드는 2차원 배열을 사용하여 dp가장 긴 공통 하위 시퀀스의 길이를 기록합니다. 현재 문자가 같은지 여부에 따라 문자열 text1및 을 순회하여 배열 값을 업데이트합니다. 마지막으로 가장 긴 공통 하위 시퀀스의 길이로 반환됩니다.text2dpdp[m][n]

위의 코드는 가장 긴 공통 서브 시퀀스 문제만 해결한다는 점에 유의하십시오.단지 길이가 아닌 특정 최장 공통 서브 시퀀스 자체를 가져와야 하는 경우 몇 가지 추가 작업이 필요합니다. 이 예제가 도움이 되길 바랍니다!

추천

출처blog.csdn.net/weixin_42499608/article/details/131318979