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, is a subsequence of and is not "ACE"
"ABCDE"
"AEC"
).
Here are an example:
S = "rabbbit"
, T ="rabbit"
Return 3
.
Use the dynamic programming algorithm to consider the topic. Because if the substring of T is known to distinct the number of subsequences in S and its substrings, then the number of distinct subsequences in S can be calculated. The key is how to find the transfer function.
Using the examples in the topic, consider the simple case, when S=rab,t=rab, is obviously number=1. When S=rabb (add one more), the original number will still have, because Rab still can match with Rab. However, since the new character is the same as the last character of T, this time the last character of T can match the newly added characters, which is not in the previous situation, need extra consideration. Then, the extra distinct subsequences number should be excluded from the last character of T (match new characters go) and s in the number of newly added characters, that is, the case of S=rab,t=ra. The total number is the original number plus the S=rab,t=ra case.
If s extra one is not the last character of T, then there will be no more out of the case, this time the number of distinct subsequences should be the original number.
Create a two-dimensional array, DP. DP[I][J] represents t.substring (0,i) and s.substring (0,j), 0<=i<=t.length (), 0<=j<=s.length ().
DP[I][J] = dp[i][j-1]//Original condition
+ dp[i-1][j-1]//If T.charat (i-1) ==s.charat (j-1)
The starting condition is dp[0][j]=1 because the number of matches is always 1 when T is an empty string.
Dp[i][j]=0 if j<i because when T length is greater than s surely there is no such subsequences.
The code is as follows:
1 Public intnumdistinct (String S, String T) {2 if(T.length () >s.length ())3 return0;4 int[] DP =New int[T.length () +1] [S.length () +1];5 for(intI=0;i<=t.length (); i++) {6 for(intJ=i;j<=s.length (); j + +) {7 if(i==0)8Dp[i][j]=1;9 ElseTenDP[I][J] = dp[i][j-1]+ (T.charat (i-1) ==s.charat (j-1)? dp[i-1][j-1]:0); One } A } - returndp[t.length ()][s.length ()]; -}
Because each cycle only needs to get the last DP value, you can further optimize the spatial complexity:
1 Public intnumdistinct (String S, String T) {2 intm =t.length ();3 intn =s.length ();4 if(m>N)5 return0;6 int[] DP =New int[M+1];7Dp[0] = 1;8 for(intj=1;j<=n;j++)9 {Ten for(inti=m;i>0;i--) One { ADp[i] + = (T.charat (i-1) ==s.charat (j-1))? dp[i-1]:0; - } - } the returnDp[m]; -}
[Leetcode] [JAVA] Distinct subsequences