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