115. Distinct Subsequences

Given a string S and a string T, count the number of distinct subsequences of T in S.

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

Here is an example: S = "rabbbit", T = "rabbit"

Return 3.

Solution: DP

class Solution(object):
    def numDistinct(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: int
        """
        if len(s) < len(t):
            return 0

        cols = len(s) + 1
        rows = len(t) + 1

        # dp[i][j]: number of distinct t[:i] in s[:j]
        dp = [[0] * cols for _ in xrange(rows)]
        for col in xrange(cols):
            dp[0][col] = 1

        for row in xrange(1, rows):
            for col in xrange(row, cols):
                dp[row][col] = dp[row][col - 1]
                if s[col - 1] == t[row - 1]:
                    dp[row][col] += dp[row - 1][col - 1]
        return dp[-1][-1]

Lessons:

  • First row is all 1 because there is only one way to turn a string into an empty string: remove every character.

results matching ""

    No results matching ""