Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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).
Example 1:
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:
As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
Example 2:
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^
第一到hard难度的题
其实也是一道水题,
首先我用了暴力深搜,果然超时,效率是(最差情况)s的长度:n,t的长度:m
O(n) = n*(n-1)*(n-2)*...(n-m+1)*m
正确的解法应该是前缀和,
遍历t字符串中的每个字符ti 找到ti 在s字符串中的位置si,统计si的前缀和sss,这里的前缀和是值si前面有多少个满足的条件的t的前缀字符串,
O(n)= n * m
c++
class Solution {
public:
int result;
int sss[100005];//ss数组的前缀和数组
int ss[100005];//当前字符串前面满足条件的前缀字符串的个数
int numDistinct(string s, string t) {
int lens = s.length();
int lent = t.length();
memset(sss,0,sizeof(sss));
for(int j=0;j<lent;j++)
{
memset(ss,0,sizeof(ss));
for(int i=j;i<lens;i++)
{
if(s[i]==t[j])
{
ss[i]=(j==0?1:sss[i-1]);
}
}
for(int i=0;i<lens;i++)
{
if(i==0){sss[i]=ss[i];continue;}
sss[i]=sss[i-1]+ss[i];
}
}
for(int i=0;i<lens;i++)
{
result += ss[i];
}
return result;
}
};