LCS 问题的解决办法

代码如下:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // for max() function
#include <utility>


using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::pair;

int lcs(const string &s1, const string &s2, int m, int n) {
    if (m < 0 || n <0) return 0;
    if (s1[m] == s2[n]) return 1 + lcs(s1, s2, m-1, n-1);
    else return std::max(lcs(s1, s2, m - 1, n), lcs(s1, s2, m, n - 1));
}


int lookUp(const vector<vector<int>> &t, int i, int j) {
        if (i < 0 || j < 0) return 0;
        else return t[i][j];
}

pair<int, string> lcsDP(const string &s1, const string &s2, int m, int n) {
    vector<vector<int>> t(s1.length(), vector<int> (s2.length()));

    for (int i = 0; i < static_cast<int>(s1.length()); ++i) {
        for (int j = 0; j < static_cast<int>(s2.length()); ++j) {
            if (s1[i] ==s2[j]) t[i][j] = lookUp(t, i - 1, j - 1) + 1;
            else t[i][j] = std::max(lookUp(t, i - 1, j),
                                    lookUp(t, i, j - 1));
        }
    }
    int i = s1.length() - 1, j = s2.length() - 1;
    string result = "";
    while(i >= 0 || j >= 0) {
        if (s1[i] == s2[j]) {
            result.push_back(s1[i]);
            --i;
            --j;
         } else {
             if (lookUp(t, i - 1, j) > lookUp(t, i, j -1)) {
                 --i;
             } else {
                 --j;
             }

         }
    }
    std::reverse(result.begin(), result.end());
    return pair<int,string> (t[s1.length() -1][s2.length() - 1], result);
}


int main()
{
    string s1 = "aaaabbcbcbc";
    string s2 = "aasdjkahgfadfbfgsgebsbsbbc";

    auto p = lcsDP(s1, s2, s1.length() - 1, s2.length() - 1);
    cout << p.first << " " << p.second << endl;

    return 0;
}

运行结果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值