最长公共子序列(二)_牛客题霸_牛客网 (nowcoder.com)
dp[i][j]指的是 s1以i结尾,s2以j结尾的字符串 的最长公共子序列长度
b[i][j] 数组相加的方向
#include <vector> class Solution { public: /** * longest common subsequence * @param s1 string字符串 the string * @param s2 string字符串 the string * @return string字符串 */ string x = ""; string y = ""; string ans(int i, int j,vector<vector<int> >&b){ string res = ""; if(i == 0 || j == 0) return res; if(b[i][j] == 1){ res += ans(i - 1, j - 1,b); res += x[i-1]; }else if(b[i][j] == 2) res += ans(i - 1, j,b); else if(b[i][j] == 3) res += ans(i, j-1,b); return res; } string LCS(string s1, string s2) { // write code here if(s1.length() == 0 || s2.length() == 0) return "-1"; int len1 = s1.length(); int len2 = s2.length(); x = s1; y = s2; vector<vector<int> >dp(len1 + 1, vector<int>(len2 + 1,0)); vector<vector<int>> b(len1 + 1, vector<int>(len2 + 1, 0)); for(int i = 1; i<= len1; i++){ for(int j = 1; j<= len2; 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; } } } } string res = ans(len1,len2,b); return res != "" ? res : "-1"; } };