当前位置:   article > 正文

算法学习——子序列性质相关经典算法

子序列性质
Longest Common Subsequence(LCS,最长公共子序列
  • DP算法
  • 状态f[i][j]: 字符串A前i个字符和字符串B前j个字符的LCS
  • 转移方程:
    if A[i-1] != B[j-1],
    f[i][j]=max{f[i1][j],f[i][j1],f[i1][j1]}

    if A[i-1] == B[j-1],
    f[i][j]=max{f[i1][j],f[i][j1],f[i1][j1]+1}
  • Code:
int longestCommonSubsequence(string &A, string &B) {
        // case 1
        if(A.empty() || B.empty()) return 0;

        // case 2
        int n = A.size(), m = B.size();
        // init null has 0 common subsequence with others
        vector<vector<int>> f(n+1, vector<int>(m+1, 0));

        for(int i=1; i<=n; ++i){
            for(int j=1; j<=m; ++j){
                if(A[i-1] == B[j-1])
                    f[i][j] = max(max(f[i-1][j], f[i][j-1]), f[i-1][j-1]+1);
                else{
                    f[i][j] = max(max(f[i-1][j], f[i][j-1]), f[i-1][j-1]);
                }
            }
        }

        return f[n][m];
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
Longest Palindromic Subsequence(最长回文子序列)
Longest Increasing Continuous Subsequence(最长连续上升子序列)
Longest Increasing Subsequence(最长上升子序列)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1004854
推荐阅读
相关标签
  

闽ICP备14008679号