Topic:
Given a string S and a string T, count the number of distinct subsequences of s which equals T.
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
.
test instructions and analysis: Given the string s and T, there are several ways to get t after removing certain characters in S. Using a dynamic programming approach, use an array of men[s.length+1][t.length+1] to hold the number of s from the start position to the I and t from the start to the J to match, i.e. how many sub-sequences of T (0,J) are contained in S (0,i).
There are three kinds of situations:
1, i==0, that is, S is empty, then men[0][j]=0
2, j==0, that is, T is empty, then men[i][0]=1
3, for i>0&&j>0 have:
(1) if S.charat (i-1)!=t.chatat (j-1), then the I-point of S to join the effect is the same, that is, men[i][j] = Men[i-1][j]
(2) if S.charat (i-1) ==t.chatat (j-1), then the current character can choose to match or mismatch, so men[i][j] = Men[i-1][j-1] + men[i-1][j];
Code:
classSolution { Public intnumdistinct (string s, String t) {int[] men =New int[S.length () +1] [T.length () +1];//Men[i][j] Represents the number of matches from the start position to the i,t from the start position to the J substring, which can be obtained men[i][j]>=men[i-1][j]//when I is 0, that is, the s substring is empty, men[i][j]==0 for(intJ=0;j<t.length (); j + +) {men[0][J] =0; } //when J=0, that is, the T substring is empty, men[i][j]=1 for(intI=0;i<s.length (); i++) {men[i][0] = 1; } for(intI=1;i<=s.length (); i++){ for(intJ=1;j<=t.length (); j + +) {Men[i][j]= Men[i-1][j]; if(S.charat (i-1) ==t.charat (j-1) ) {Men[i][j]+ = Men[i-1][j-1]; } } } returnmen[s.length ()][t.length ()]; }}
[Leetcode] 115. Distinct subsequences Java