Distinct subsequences
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
.
I wrote a deep-first recursive program, TLE. The leetcode requirement is really high ..
The space is changed to time, and DP is used for this. That is to say, a recursive condition is used to obtain the relationship between N-1 and n steps.
The recursive condition is set to the first I characters of S. The conversion method of the first J characters of T is obtained by deleting the characters. The two-dimensional array element transarr [I] [J] is used for recording.
(1) If s [I] = T [J], add s [I] and T [J] To s [0 ~ I-1] and T [0 ~ The J-1] can fully replicate the transarr [I-1] [J-1] type conversion method. In addition, s [0 ~ I-1] itself (without adding s [I]) can also be converted to T [0 ~ I-1] [J] Mode ~ J].
Transarr [I] [J] = transarr [I-1] [J-1] + transarr [I-1] [J];
(2) If s [I]! = T [J], meaning s [I] cannot be used for conversion to T [0 ~ J], t [J] needs to be from S [0 ~ I-1], so s [0 ~ I] and S [0 ~ I-1.
Transarr [I] [J] = transarr [I-1] [J];
However, the above conditions are not enough. The result of transarr [m] [N] is the accumulation of 0. Therefore, you need to define the initial value.
If transarray [I] [0] is set to 1, it means that if it is converted to an empty string of any length, it means to delete all characters in 1.
class Solution {public: int numDistinct(string S, string T) { int m = S.size(); int n = T.size(); vector<vector<int>> transArr(m+1, vector<int>(n+1, 0)); for(int i = 0; i < m+1; i ++) transArr[i][0] = 1; for(int i = 1; i < m+1; i ++) { for(int j = 1; j < n+1; j ++) { if(S[i-1] == T[j-1]) transArr[i][j] = transArr[i-1][j-1]+transArr[i-1][j]; else transArr[i][j] = transArr[i-1][j]; } } return transArr[m][n]; }};