最长公共子序列(动态规划)--算法学习
发布日期:2021-05-15 00:27:57 浏览次数:21 分类:精选文章

本文共 2513 字,大约阅读时间需要 8 分钟。

���������������������������������������������������������������������������������������������������������������������������������������������������������������������������

��������������� ��������������������������������������������������������������� MaxLen(i, j) ������ i ������������������������������������������ j ������������������������������������������������������������������������

  • ���������������

    • ��� i ��� j ��� 0 ��������������������� 0������������������������������������
  • ���������������

    • ������ s1[i-1] == s2[j-1]������ MaxLen(i, j) = MaxLen(i-1, j-1) + 1���
    • ���������MaxLen(i, j) = Max(MaxLen(i, j-1), MaxLen(i-1, j))���������������������������������
  • ���������������

    • ������������������������ maxLen������������������������������������������ 1��������������� 0���
    • ������������������������������������������ i ��� j���������������������������������������������
  • ���������������

    #include 
    #include
    using namespace std;
    int maxChar(const char* s1, const char* s2, int& i, int& j) {
    if (s1[i] == s2[j]) {
    return 1; // ������1���������������������������������
    } else if (s1[i] < s2[j]) {
    i++; // ������s1������������������������������������������
    } else {
    j++; // ������s2������������
    }
    return 0; // ���������������������������
    }
    int main() {
    string s1, s2;
    while (cin >> s1) {
    cin >> s2;
    int len1 = s1.length(), len2 = s2.length();
    int maxLen[ len1 +1 ][ len2 +1 ]; // ���������������������������������len1+1 x len2+1
    int i = 0, j = 0;
    for (int x = 0; x <= len1; x++) {
    for (int y = 0; y <= len2; y++) {
    if (x == 0 || y == 0) {
    maxLen[x][y] = 0;
    } else if (s1[x-1] == s2[y-1]) {
    maxLen[x][y] = maxLen[x-1][y-1] + 1;
    } else {
    maxLen[x][y] = max(maxLen[x-1][y], maxLen[x][y-1]);
    }
    }
    }
    cout << maxLen[len1][len2] << endl;
    }
    return 0;
    }

    ���������������

  • ��������������� ��������������������������� s1 ��� s2���
  • ������������������������ ������������ maxLen ������������ size ��� len1+1 ��� len2+1��������������� 0���
  • ��������������������� ������������������������ i ��� j��������������������������������������������������������� maxLen ������
  • ��������������� ������ maxLen[len1][len2] ������������������������������������������������������
  • ��������������������������������� O(mn)���������������������������������������������

    上一篇:Help Jimmy(动态规划)--算法学习
    下一篇:最长上升子序列(动态规划)--算法学习

    发表评论

    最新留言

    能坚持,总会有不一样的收获!
    [***.219.124.196]2025年04月17日 06时52分22秒