代码如下:
#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;
}
运行结果如下: