LeetCode 115 Distinct Subsequences (C++, Python)

Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
Here is an example:
S = "rabbbit"T = "rabbit"


solution C++


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    int numDistinct(string s, string t) {
        const int M = s.length();
        const int N = t.length();
        if (M < N) return 0;
        //vector<vector<int>> dp(M + 1, vector<int>(N + 1, 0));
        int dp[N + 1] = {0};
        dp[N] = 1;
        for (int i = M - 1; i >= 0; --i) {
            for (int j = 0; j < N; ++j) {
                dp[j] += (s[i] == t[j]) * dp[j + 1];
            }
        }
        return dp[0];
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    # @param {string} s
    # @param {string} t
    # @return {integer}
    def numDistinct(self, s, t):
        M = len(s)
        N = len(t)
        if M < N: return 0
        dp = [0] * N + [1]
        for i in range(M - 1, -1, -1):
            for j in range(N):
                dp[j] += dp[j + 1] * (s[i] == t[j])
        return dp[0]

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving