115. Distinct Subsequences - cocoder39/coco39_LC GitHub Wiki

115. Distinct Subsequences

we want dp[m][n] to represent the number of sequence t that s contains. Thus our dp[i][j] is the number of sequence t[0 .. j - 1] that s[0 .. i - 1] contains. the key point of induct dp[i][j] is checking if s[i - 1] == t[i - 1].

int numDistinct(string s, string t) {
        int m = s.length();
        int n = t.length();
        //dp[i][j] is the number of sequence t[0 .. j - 1] that s[0 .. i - 1] contains
        vector<vector<int>> dp(m + 1, vector<int>(n + 1));
        
        for (int i = 0;  i <= m; i++) {
            dp[i][0] = 1; //any sequence contains empty
        }
        for (int j = 1; j <= n; j++) {
            dp[0][j] = 0; //empty cannot contain any non-empty 
        }
        
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                dp[i][j] = dp[i - 1][j] + (s[i - 1] == t[j - 1] ? dp[i - 1][j - 1] : 0); 
            }
        }
        return dp[m][n];
    }

optimize memory through rolling array

int numDistinct(string s, string t) {
        int m = s.length();
        int n = t.length();
        //dp[i][j] is the number of sequence t[0 .. j - 1] that s[0 .. i - 1] contains
        vector<vector<int>> dp(2, vector<int>(n + 1));
        
        for (int j = 1; j <= n; j++) {
            dp[0][j] = 0; //empty cannot contain any non-empty 
        }
        
        int pre = 0, cur = 1;
        for (int i = 1; i <= m; i++) {
            dp[pre][0] = 1;
            dp[cur][0] = 1;
            for (int j = 1; j <= n; j++) {
                dp[cur][j] = dp[pre][j] + (s[i - 1] == t[j - 1] ? dp[pre][j - 1] : 0); 
            }
            swap(pre, cur);
        }
        return dp[pre][n];
    }
⚠️ **GitHub.com Fallback** ⚠️