题解 | #最长公共子序列(二)#
最长公共子序列(二)
https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11
#include <functional>
#include <vector>
class Solution {
public:
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
string LCS(string s1, string s2) {
int n1 = s1.length();
int n2 = s2.length();
vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1));
vector<vector<int>> b(n1 + 1, vector<int>(n2 + 1));
for (int i = 1; i <= n1; ++i) {
for (int j = 1; j <= n2; ++j) {
if (s1[i - 1] == s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
b[i][j] = 1;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
dp[i][j] = dp[i - 1][j];
b[i][j] = 2;
} else {
dp[i][j] = dp[i][j - 1];
b[i][j] = 3;
}
}
}
function<string(int, int)> getres = [&](int i, int j) -> string {
if (i == 0 || j == 0) {
return "";
}
string res;
switch (b[i][j]) {
case 1: {
res = getres(i - 1, j - 1) + s1[i - 1];
} break;
case 2: {
res = getres(i - 1, j);
} break;
case 3: {
res = getres(i, j - 1);
} break;
}
return res;
};
return getres(n1, n2) == ""? "-1": getres(n1, n2);
}
};
思路:动态规划。
在求最长公共子序列时,记录子序列扩展的方向,以在找到公共子序列最长的长度后,反向求出该子序列。
查看1道真题和解析