115. distinct subsequence leetcode python

來源:互聯網
上載者:User

標籤:leetcode   dp   python   

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.

This problem is a typical dp problem.. we need to maintain  a dp array to find the result by sequence.

here I have two approaches one I need to use O(m.n) space one need to just use O(m) space.

The time complexity is always the same. O(m.n) because we need to travesal the two strings

the first method is to  maintain DP[n][m]


code is as follow

class Solution:    # @return an integer    def numDistinct(self, S, T):        dp=[[0 for j in range(len(T)+1)] for i in range(len(S)+1)]        for i in range(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-1]+dp[i-1][j]                else:                    dp[i][j]=dp[i-1][j]        return dp[-1][-1]




second method saves more space but we need to reversed the order

class Solution:    # @return an integer    def numDistinct(self, S, T):        if len(S)==0:            return 0        if len(T)==0:            return 1###         res=[0 for j in range(len(T)+1)]        res[0]=1        for  i in range(len(S)):            for j in reversed(range(len(T))):                if S[i]==T[j]:                    res[j+1]=res[j]+res[j+1]        return res[len(T)]                        


115. distinct subsequence leetcode python

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.