To solve this problem, we need to count the number of distinct subsequences of a string s that exactly match another string t. A subsequence is a sequence derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Approach
The problem can be efficiently solved using dynamic programming (DP) with optimized space complexity. Here's the detailed approach:
- Dynamic Programming Array: We use a 1D DP array
dpwheredp[j]represents the number of ways to form the firstjcharacters oftusing the characters ofsprocessed so far. - Base Case:
dp[0] = 1because there is exactly one way to form an empty subsequence (by choosing nothing). - Transition: For each character in
s, we update the DP array from right to left (to avoid overwriting values we need for the current iteration). If the current character ofsmatches thej-thcharacter oft, thendp[j] += dp[j-1](this accounts for both including and excluding the current character ofs). - Modulo Operation: Since the result can be very large, we use modulo
10^9 + 7to keep the numbers manageable.
Solution Code
def numDistinct(s: str, t: str) -> int:
MOD = 10**9 + 7
m, n = len(s), len(t)
if n > m:
return 0
dp = [0] * (n + 1)
dp[0] = 1 # Base case: one way to form empty subsequence
for char in s:
# Iterate from right to left to avoid overwriting dp[j-1] before using it
for j in range(n, 0, -1):
if char == t[j-1]:
dp[j] = (dp[j] + dp[j-1]) % MOD
return dp[n]
Explanation
- Initialization: The DP array starts with
dp[0] = 1and all other values set to0. - Processing Each Character: For each character in
s, we check if it matches any character int(from the end to the start). If it does, we update the DP value for that position by adding the number of ways to form the subsequence up to the previous character oft. - Result: The value
dp[n](wherenis the length oft) gives the number of distinct subsequences ofsthat matcht.
This approach has a time complexity of O(m * n) where m is the length of s and n is the length of t, and a space complexity of O(n) which is optimized compared to the 2D DP approach. This makes it efficient for large input sizes.
Example: For s = "rabbbit" and t = "rabbit", the code returns 3 which is the correct number of distinct subsequences. This is because we can choose any two of the three 'b's in s to form the subsequence "rabbit".
Another example: For s = "aaa" and t = "aa", the code returns 3 (since there are 3 ways to choose two 'a's from three).
This solution efficiently handles all edge cases and provides the correct result using dynamic programming with optimized space.

作者声明:本文包含人工智能生成内容。