递归式:
c[i-1][j]还是c[i][j-1]。
代码:
int Lcs(string &s1,string &s2, int i, int j,int** &arr) { if (arr == nullptr) { arr = new int*[s1.length()+1]; for (int i = 0; i <= s1.length(); i++) { arr[i] = new int[s2.length()+1]; } for (int i = 0; i <= s1.length(); i++) { arr[i][0] = 0; for (int j = 0; j <= s2.length(); j++) { arr[0][j] = 0; if (i >= 1 && j >= 1) { arr[i][j] = -1; } } } } if (i == 0 || j == 0) { arr[i][j] = 0; return arr[i][j]; } if (arr[i][j] != -1) { return arr[i][j]; } if (s1[i-1] == s2[j-1]){ arr[i][j]= Lcs(s1, s2, i - 1, j - 1,arr) + 1; } else { arr[i][j]= max(Lcs(s1, s2, i - 1, j,arr), Lcs(s1, s2, i, j - 1,arr)); } return arr[i][j]; } string findstr(string &s1, string &s2, int **arr) { if (arr == nullptr) { return ""; } int slen1 = s1.length(); int slen2 = s2.length(); string result = ""; for (int i = slen1; ;) { for (int j = slen2; ;) { if (arr[i][j]==0) { return result; } if (s1[i-1] == s2[j-1]) { result += s1[i - 1]; --i, --j; } else { if (arr[i - 1][j] < arr[i][j - 1]) { i--; } else { j--; } } } } } int main() { string s1 = "ABCBDAB", s2 = "BDCABA"; const int slen1 = s1.length(), slen2 = s2.length(); int **arr = nullptr; cout << "长度为" << Lcs(s1, s2, slen1, slen2,arr) << endl; for (int i = 0; i <= slen1; i++) { for (int j = 0; j <= slen2; j++) { cout << arr[i][j] << " "; } cout << endl; } cout << findstr(s1, s2, arr); for (int i = 0; i <= slen1; i++) { delete[] arr[i]; } delete[] arr; return 0; }
结果:
文章来源: 动态规划-最长子序列