缩小问题规模

lcs(str1, str2, m, n)
画递归树

构造状态转移

递归实现

memoization 自上而下

理解递归矩阵

tabulation 自下而上(制表法)

三种方法代码

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

using namespace std;

// 递归实现
int lcs_recursive(string str1, string str2, int m, int n)
{
    int tmp;
    if (m == 0 || n == 0)
        return 0;
    if (str1[m - 1] == str2[n - 1])
    {
        tmp = 1 + lcs_recursive(str1, str2, m - 1, n - 1);
        return tmp;
    }
    else
    {
        tmp = max(lcs_recursive(str1, str2, m - 1, n), lcs_recursive(str1, str2, m, n - 1));
        return tmp;
    }
}

// memoization 自上而下
int lcs_memoization(string str1, string str2, int m, int n)
{
    int tmp;
    // 初始为-1
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, -1));
    if (m == 0 || n == 0)
    {
        dp[m][n] = 0;
        return 0;
    }
    if (dp[m][n] != -1)
        return dp[m][n];
    if (str1[m - 1] == str2[n - 1])
    {
        tmp = 1 + lcs_recursive(str1, str2, m - 1, n - 1);
        dp[m][n] = tmp;
        return tmp;
    }
    else
    {
        tmp = max(lcs_recursive(str1, str2, m - 1, n), lcs_recursive(str1, str2, m, n - 1));
        dp[m][n] = tmp;
        return tmp;
    }
}

// tabulation 自下而上
int lcs_tabulation(string str1, string str2, int m, int n)
{
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    for (int i = 1; i < m + 1; ++i)
    {
        for (int j = 1; j < n + 1; ++j)
        {
            if (str1[i - 1] == str2[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()
{
    // input string
    string str1;
    string str2;
    cout << "Input 2 String:" << endl;
    cin >> str1 >> str2;
    cout << "The length of longest common subsequence is: " << lcs(str1, str2, str1.length(), str2.length()) << endl;
    return 0;
}



扫一扫在手机打开当前页