美文网首页
77. Longest Common Subsequence

77. Longest Common Subsequence

作者: 刘小小gogo | 来源:发表于2018-09-06 00:26 被阅读0次
    image.png
    参考 https://algorithm.yuanbin.me/zh-hans/dynamic_programming/longest_common_subsequence.html
    image.png

    状态转移方程:

    c[i][j] =
    (1) 0 if i == 0 && j == 0
    (2) c[i - 1][j - 1] + 1, if A[i] == B[j]
    (3) max(c[i][j - 1], c[i - 1][j]) if A[i] != B[j]

    class Solution {
    public:
        /**
         * @param A: A string
         * @param B: A string
         * @return: The length of longest common subsequence of A and B
         */
        int longestCommonSubsequence(string &A, string &B) {
            // write your code here
            if(A.empty()) return 0;
            if(B.empty()) return 0;
            int lenA = A.size();
            int lenB = B.size();
            vector<vector<int>> dp(lenA + 1);
            for(int i = 0; i < lenA + 1; i++){
                dp[i].resize(lenB + 1, 0);
            }
            for(int i = 1; i < lenA + 1; i++){
                for(int j = 1; j < lenB + 1; j++){
                    if(A[i - 1] == B[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
                    else{
                        dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                    }
                }
            }
            return dp[lenA][lenB];
        }
    };
    

    相关文章

      网友评论

          本文标题:77. Longest Common Subsequence

          本文链接:https://www.haomeiwen.com/subject/ddctgftx.html