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
.
动态规划!
1 class Solution { 2 public: 3 int numDistinct(string S, string T) { 4 vector<vector<int> > a(T.length() + 1, vector<int>(S.length() + 1)); 5 for (int j = 0; j <= S.length(); ++j) { 6 a[0][j] = 0; 7 } 8 for (int i = 0; i <= T.length(); ++i) { 9 a[i][0] = 0; 10 } 11 for (int i = 1; i <= S.length(); ++i) { 12 if (S[i-1] == T[0]) { 13 a[1][i] = a[1][i-1] + 1; 14 } else { 15 a[1][i] = a[1][i-1]; 16 } 17 } 18 for (int i = 2; i <= T.length(); ++i) { 19 for (int j = 1; j <= S.length(); ++j) { 20 if (T[i-1] == S[j-1]) { 21 a[i][j] = a[i-1][j-1] + a[i][j-1]; 22 } else { 23 a[i][j] = a[i][j-1]; 24 } 25 } 26 } 27 return a[T.length()][S.length()]; 28 } 29 };
其实最开始的想法是dfs,果段超时。比起动规来还是递归好写一点,动规还不太熟练,得加油啊。
1 class Solution { 2 public: 3 void dfs(string &S, int idxs, string &T, int idxt, int &res) { 4 if (idxt == T.length()) { 5 ++res; 6 return; 7 } 8 if (idxs == S.length()) { 9 return; 10 } 11 if (S[idxs] == T[idxt]) { 12 dfs(S, idxs + 1, T, idxt + 1, res); 13 } 14 dfs(S, idxs + 1, T, idxt, res); 15 } 16 17 int numDistinct(string S, string T) { 18 int res = 0; 19 dfs(S, 0, T, 0, res); 20 return res; 21 } 22 };