[LeetCode-115] Distinct Subsequences
Distinct Subsequences
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 of"ABCDE"
while "AEC"
is not).
Here is an example:
S = "rabbbit"
, T = "rabbit"
Return 3
.
一开始历遍,妥妥的超时,后来用了DP……代码说话吧……
1 class Solution { 2 public: 3 4 /* 妥妥的太慢 5 void tryStr(string str, const string& T, int & result) { 6 if (str.length() < T.length()) { 7 return; 8 } 9 else if (str.length() > T.length()) { 10 tryStr(str.substr(0, i) + str.substr(i + 1, str.length() - i), T, result); 11 } 12 else if (0 == str.compare(T)) { 13 ++result; 14 } 15 } 16 int numDistinct(string S, string T) { 17 // Start typing your C/C++ solution below 18 // DO NOT write int main() function 19 int result = 0; 20 tryStr(S, T, result); 21 return result; 22 } 23 */ 24 25 int numDistinct(string S, string T) { 26 // Start typing your C/C++ solution below 27 // DO NOT write int main() function 28 int slen = S.length(); 29 int tlen = T.length(); 30 if (tlen > slen) 31 { 32 return 0; 33 } 34 int **dp = new int*[tlen]; 35 for (int i = 0; i < tlen; ++i) 36 { 37 dp[i] = new int[slen]; 38 memset(dp[i], 0, slen * sizeof(int)); 39 } 40 dp[0][0] = ((S[0] == T[0]) ? 1 : 0); 41 for (int j = 1; j < slen; ++j) 42 { 43 dp[0][j] = dp[0][j - 1] + ((T[0] == S[j]) ? 1 : 0); 44 } 45 for (int i = 1; i < tlen; ++i) 46 { 47 for (int j = 1; j < slen; ++j) 48 { 49 dp[i][j] = dp[i][j - 1] + ((T[i] == S[j]) ? dp[i - 1][j - 1] : 0); 50 } 51 } 52 53 int result = dp[tlen - 1][slen - 1]; 54 for (int i = 0; i < tlen; ++i) 55 { 56 delete [] dp[i]; 57 } 58 delete [] dp; 59 return result; 60 } 61 };