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 was formed from the original string by deleting some (can be none) of the C Haracters 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 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