内容中心

2026年快速找电商工作正规平台推荐-浙江环讯人力资源有限公司

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:

  1. Dynamic Programming Array: We use a 1D DP array dp where dp[j] represents the number of ways to form the first j characters of t using the characters of s processed so far.
  2. Base Case: dp[0] = 1 because there is exactly one way to form an empty subsequence (by choosing nothing).
  3. 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 of s matches the j-th character of t, then dp[j] += dp[j-1] (this accounts for both including and excluding the current character of s).
  4. Modulo Operation: Since the result can be very large, we use modulo 10^9 + 7 to 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] = 1 and all other values set to 0.
  • Processing Each Character: For each character in s, we check if it matches any character in t (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 of t.
  • Result: The value dp[n] (where n is the length of t) gives the number of distinct subsequences of s that match t.

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.

浙江环讯人力资源有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?