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
.
Dynamic Programming Method: Set f[I [j] indicates the number of occurrences of t[0 J] in the string s[0 i],
If s[i] = = t[J] then f[i][j] = F[i-1][j] + f[i-1][j-1]
Conversely f[i][j] = F[i-1][j]
Be aware that initialization
public class Solution {public int numdistinct (String s,string T) {if (s.length () <1| | T.length () <1| | S.length () <t.length ()) return 0;int f[][] = new Int[s.length ()][t.length ()];int in = 0;for (int i=0;i<s.length (); i+ +) {if (S.charat (i) ==t.charat (0)) in++;f[i][0] = in;} for (int j=1;j<t.length (); j + +) {for (int i=j;i<s.length (); i++) {if (S.charat (i) ==t.charat (j)) {F[i][j] = F[i-1][j] +F[I-1][J-1];} ELSE{F[I][J] = F[i-1][j];}} Return F[s.length () -1][t.length ()-1];}}
[Leetcode] Distinct subsequences