115. Distinct Subsequences 不同的subsequence

115. Distinct Subsequences 

Given two strings s and t, return the number of distinct subsequences of s which 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).

The test cases are generated so that 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:

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


機車題

定義dp[i][j] 為 s[:i] 子串 可以形成t[:j]的數量
邊界條件:如果t為空
則dp[i][0]=1 for all i,

之後討論:
如果 s[i]==t[j]: 要計算dp[i+1][j+1]
表示 s可以使用s[i]跟t[j],所以貢獻dp[i][j]
或是 s可以不使用s[i],所以又貢獻dp[i][j+1]

假設 s[i]不等於t[j]
那肯定不能用s[i]
所以只有dp[i][j+1]

最後 
dp[i+1][j+1]就用上面來計算:


可以參考以下code


class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        
        m=len(s)
        n=len(t)
        
        dp=[[0]*(n+1) for i in range(m+1)]
        
        for i in range(m+1):
            dp[i][0]=1
        
        for i in range(m):
            for j in range(n):
                if s[i]==t[j]:
                    dp[i+1][j+1]=dp[i][j+1]+dp[i][j]
                else:
                    dp[i+1][j+1]=dp[i][j+1]
                    
        return dp[-1][-1]

留言

這個網誌中的熱門文章

1041. Robot Bounded In Circle 機器人在圈圈裏面?

382. Linked List Random Node: 隨機選元素從list裡面

2134. Minimum Swaps to Group All 1's Together II 使得所有1連在一起