title :(DP)
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 .
The following:
The meaning of the title must be understood first: given two strings S and T, how many different substrings of s are the same as T. The substring of S is defined as a string that is arbitrarily stripped of 0 or more characters in S.
Then there is a central idea to this type of problem:
When you see the string problem that's about subsequence or matching, the dynamic programming method should come to your mind NA Turally. ”
Reference http://www.cnblogs.com/springfor/p/3896152.html
First, set the dynamic Plan array Dp[i][j], which represents the number of sub-sequences in the S string from the start position to position I and the T string from the start position to the exact J position.
If the S string is empty, then Dp[0][j] is 0;
If the T string is empty, then dp[i][j] is 1 because the empty string is a string of any strings.
Can find the law, dp[i][j] at least equal to dp[i][j-1].
When I=2,j=1, S is ra,t for r,t is definitely the substring of s, so dp[2][1]=1, at this time i=2,j=2, S is ra,t for rs,t now is not s substring dp[2][2] =dp[1][2]=0
Then a is not equal to s so dp[2][2]=0;
Also, if the string s[i-1] and T[j-1] (DP is counted starting from 1, the string is counted from 0), Dp[i][j] plus dp[i-1][j-1]
For example, for example: S = "rabbbit" , T ="rabbit"
When I=2,j=1, S is ra,t for r,t is definitely the substring of S, and when i=2,j=2, S is still ra,t as RA, then T is also the substring of s, so the number of substrings is added dp[2][1] on the basis of dp[1][1].
Public intnumdistinct (String S, String T) {2 int[] DP =New int[S.length () +1][t.length () +1]; 3dp[0][0] =1;//Initial 4 5 for(intj =1; J <= T.length (); J + +)//S is empty 6dp[0][J] =0; 7 8 for(inti =1; I <= s.length (); i++)//T is empty 9dp[i][0] =1;Ten One for(inti =1; I <= s.length (); i++) { A for(intj =1; J <= T.length (); J + +) { -DP[I][J] = dp[i-1][j]; - if(S.charat (I-1) = = T.charat (J-1)) theDP[I][J] + = dp[i-1][j-1]; - } - } - + returndp[s.length ()][t.length ()]; -}
[Leetcode] Distinct subsequences