题目:
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.
题意:
给定一个字符串S和T,计算T在S中的所有子序列个数。子序列不是子串,无需连续。
思路:
这道题采用动态规划思想。保存二维数组DP[i][j] 其中i代表的是匹配到T的下标i的字符,j代表时从S的下标0到下标j,即j+1长度的字符串拥有的T的前i+1字符串的子序列的个数。首先必须是j >= i,不然S中的字符个数都没有T中的多的话,肯定无法从前j+1个中找出前i+1的字符的子串。如果T[i] == S[j]的话,那么转移方程就是DP[i][j] = DP[i-1]j-1] + DP[i][j-1].即S的第j+1个字符是否用作在匹配T的子序列中。如果T[i] != S[j]的话,那么DP[i][j] = DP[i][j-1];
具体来说转移方程如下:
- DP[i][j] = DP[i-1][j-1] + DP[i][j-1] { T[i] == S[j])
- DP[i][j] = DP[i][j-1]{T[i] != S[j]}
其中关于具体的细节请参考代码:
以上。
代码如下:
class Solution {
public:
int numDistinct(string s, string t) {
if(s.size() < t.size() || t.size() == 0)return 0;
DP = new int*[t.size()];
for(int i = 0; i < t.size(); i++){
DP[i] = new int[s.size()];
}
for(int i = 0; i < t.size(); i++)
for(int j = i; j < s.size() - (t.size() - i - 1); j++){
if(t[i] == s[j]){
DP[i][j] = ((i > 0)?DP[i-1][j-1]:1) + ((j > i)?DP[i][j-1]:0);
}
else{
DP[i][j] = ((i == j)?0:DP[i][j-1]);
}
}
return DP[t.size() - 1][s.size() - 1];
}
}