Skip to content

Latest commit

 

History

History
32 lines (24 loc) · 744 Bytes

File metadata and controls

32 lines (24 loc) · 744 Bytes

115. Distinct Subsequences

Difficulty: Hard

URL

https://leetcode.com/problems/distinct-subsequences/

Solution

Approach 1: Dynamic Programming

The code is shown below:

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