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 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
.
// DFS can be used here, but, TLE. therefore, DP is used to solve the problem. // assume that the DP [I] [J] State represents the number of methods that string I converts to string J. Then, the dynamic transfer equation is: // 1) s [I-1] = T [J-1] --> DP [I] [J] = DP [I-1] [J-1] + dp [I-1] [J] // 2) s [I-1]! = T [J-1] --> DP [I] [J] = DP [I-1] [J]. class solution {public: int numdistinct (STD: String S, STD: String t) {int n = S. size (), M = T. size (); STD: vector <int> dp (n + 1, STD: vector <int> (m + 1, 0 )); for (INT I = 0; I <n + 1; I ++) {DP [I] [0] = 1;} For (INT I = 1; I <= N; I ++) {for (Int J = 1; j <= m; j ++) {If (s [I-1] = T [J-1]) DP [I] [J] = DP [I-1] [J-1] + dp [I-1] [J]; else DP [I] [J] = DP [I-1] [J] ;}} return DP [N] [m] ;}};
Leetcode-distinct subsequences