77. Longest Common Subsequence

77. Longest Common Subsequence

Tag:

Dynamic Problem

Main Idea:

DP-Match Problem. As there are two strings s1, s2, let n be the length of s1, m be the length of s2. For the problem, 0 <= i < n, 0 <= j < m.

  1. State:

    • dp[i][j]: the max LCS for the first i of s1 between first j of s2.
  2. Update Function:

    • IF s1[i] == s2[j], then dp[i][j] = 1 + dp[i-1][j-1]; ELSE, dp[i][j] = max(dp[i-1][j], dp[i][j-1])
  3. Initialization:

    1. dp[i][0] =0
    2. dp[0][j] =0
  4. Answer:
    dp[n][m]

Tips/Notes:

  1. IF s1[i] == s2[j], then dp[i][j] = 1 + dp[i-1][j-1]. Why not dp[i][j] = 1 + max( dp[i-1][j-1], dp[i][j-1], dp[i-1][j]).

Time/Space Cost:

Time Cost:   O ( n m ) \ O(nm)
Space Cost:   O ( n m ) \ O(nm)

Code:

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
        int n = A.length();
        int m = B.length();
        vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
        
        for(int i = 0; i <= n; i++){
            dp[i][0] = 0;
        }
        
        for(int j = 0; j <= m; j++){
            dp[0][m] = 0;
        }
        
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= m; j++){
                if(A[i-1] == B[j-1]){
                    dp[i][j] = 1 + dp[i-1][j-1];
                }
                else {
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        return dp[n][m];
        
    }
};

发布了10 篇原创文章 · 获赞 0 · 访问量 97

猜你喜欢

转载自blog.csdn.net/Zahb44856/article/details/103942841