Distinct subsequence Leetcode python

Source: Internet
Author: User

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 be formed from the original strings 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  = < Code style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; font-size:13px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">" 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 had the approaches one I need to the use O (M.N) space one need to the just use O (m) space.

The time complexity is always the same. O (M.N) because we need to travesal the 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 RA Nge (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 and 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)]                        


Distinct subsequence Leetcode python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.