动态规划-最长子序列

匿名 (未验证) 提交于 2019-12-03 00:27:02



递归式:


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; }

结果:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!