Skip to content

0115. Distinct Subsequences

Given two strings s and t, return the number of distinct subsequences of swhich equals t.

A string's subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., "ACE" is a subsequence of "ABCDE" while "AEC" is not).

It is guaranteed the answer fits on a 32-bit signed integer.

Example 1:

Input: s = "rabbbit", t = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
rabbbit
rabbbit
rabbbit

Example 2:

Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
babgbag
babgbag
babgbag
babgbag
babgbag

Constraints:

  • 0 <= s.length, t.length <= 1000
  • s and t consist of English letters.

Analysis

S = "rabbbit", T = "rabbit"

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^

note: can only delete

dp[i][j]: ways to transform S[0:i]to T[0:j]

  1. if t is "", then only one way to form t from s (delete all)
  2. if t[i] == s[j]: dp[i][j] = dp[i-1][j-1]+dp[i][j-1] -> t can choose either delete the current one or not, both are valid
  3. if t[i] != s[j]: dp[i][j] = dp[i][j-1] -> the extra one cannot be counted and should only use the previous stage result (delete current one)

Code

class Solution {
public:
    int numDistinct(string s, string t) {
        int m = t.length(), n = s.length();
        int64_t dp[m+1][n+1];
        memset(dp, 0, sizeof dp);
        for (int j = 0; j <= n; j++) dp[0][j] = 1;
        for (int i = 1; i <= m; i++)
            for (int j = i; j <= n; j++)
                dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);
        return dp[m][n];
    }
}; 

Last update: April 1, 2022