Problem desciption: Given a stringSAnd a stringT, Count the number of distinct subsequencesTInS.
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"ABCDE"While"AEC"Is not ).
Here is an example:
S="Rabbbit",T="Rabbit"
Return3.
Solution: Uses the idea of dynamic programming. Mat [I] [J] indicates the results of subproblem S = S. substring (0, I-1), t = T. substring (0, J-1)
1 Public Int Numdistinct (string S, string t ){ 2 Int Slen = S. Length (); 3 Int Tlen = T. Length (); 4 If (Slen = 0) Return 0; 5 If (Tlen = 0) Return 1 ; 6 Int [] [] MAT = New Int [Slen + 1] [tlen + 1 ]; 7 For ( Int I = 0; I <= slen; I ++) mat [I] [0] = 1 ; 8 For ( Int I = 1; I <= slen; I ++ ) 9 For ( Int J = 1; j <= tlen; j ++ ){ 10 If (S. charat (I-1) = T. charat (J-1 )) 11 Mat [I] [J] = mat [I-1] [J-1] + mat [I-1 ] [J]; 12 Else 13 Mat [I] [J] = mat [I-1 ] [J]; 14 } 15 16 Return Mat [slen] [tlen]; 17 }