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。
用r[i][j]表示S的前i的子串包含多少T的前j的子串。
如果S[i] == T[j], r[i][j] = r[i-1][j] + r[i-1][j-1]
如果S[i] != T[j], r[i][j] = r[i-1][j]。
代码:
1 int numDistinct(string S, string T) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 int col = S.length() + 1; 5 int row = T.length() + 1; 6 int** dp = new int*[row]; 7 for(int i = 0; i < row; ++i) 8 dp[i] = new int[col]; 9 10 for(int i = 0; i < row; ++i) 11 dp[i][0] = 0; 12 for(int j = 0; j < col; ++j) 13 dp[0][j] = 1; 14 15 for(int i = 1; i < row; ++i) 16 for(int j = 1; j < col; ++j) 17 if(T[i-1] == S[j-1]) dp[i][j] = dp[i-1][j-1] + dp[i][j-1]; 18 else dp[i][j] = dp[i][j-1]; 19 20 int tmp = dp[row-1][col-1]; 21 22 for(int i = 0; i < row; ++i) 23 delete[] dp[i]; 24 delete[] dp; 25 return tmp; 26 }
第二次
1 int numDistinct(string S, string T) { 2 // Start typing your C/C++ solution below 3 // DO NOT write int main() function 4 int ls = S.length(), lt = T.length(); 5 int res[ls+1][lt+1]; 6 int i,j; 7 for(i = 0; i <= lt; i++) 8 res[0][i] = 0; 9 for(i = 0; i <= ls; i++) 10 res[i][0] = 1; 11 for(i = 1; i <= ls; i++){ 12 for(j = 1; j <= lt; j++){ 13 if(S[i-1] == T[j-1]) 14 res[i][j] = res[i-1][j-1]+res[i-1][j]; 15 else 16 res[i][j] = res[i-1][j]; 17 } 18 } 19 return res[ls][lt]; 20 }