1. 程式人生 > >Leetcode -- 115. Distinct Subsequences

Leetcode -- 115. Distinct Subsequences

solution 邊界值 positions self urb [0 from form lee

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

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.

class Solution(object):
    def numDistinct(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: int
        """
        # 關鍵是定義各個狀態,找出狀態轉移方程
        # dp[i][j]表示字符串s[0~i-1] 中有多少個t[0~j-1].
dp = [[0 for col in range(len(t) + 1)] for row in range(len(s) + 1)] if len(t) == 0 or len(s) == 0: return 0 for i in range(len(s) + 1): # 給第一列邊界值賦值,此時為s[0],即為空時 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的維度要小1,所以為i-1,j-1 #如果S的第i個字符和T的第j個字符相同,那麽所有dp[i-1][j-1]中滿足的結果都會成為新的滿足的序列 dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] else: #假設S的第i個字符和T的第j個字符不相同,那麽就意味著dp[i][j]的值跟res[i-1][j]是一樣 dp[i][j] = dp[i - 1][j] return dp[len(s)][len(t)]

Leetcode -- 115. Distinct Subsequences