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
.
分析:
使用二维动态规划,并利用滚动数组减少空间开销。
设f[i,j] 为s[0,i]内找到t[0,j]的次数,则可以分为两种情况:
1. 不考虑s[i],则f[i,j]=f[i-1,j];
2. 考虑s[i],若s[i]==t[j],则还要加上f[i-1,j-1];
所以递推公式为:
f[i,j]=f[i-1,j]+{ s[i]==t[j]?f[i-1,j-1]:0}
根据上式,每次计算的时候实际只需要用到前一行的结果,因此没有必要完整的保存整个f[i,j]。一种方法是将f[i,j]存成两行,每次通过对2取模来决定修改哪一行;另一种方法即如以下代码所示,仅适用一行,但是从后向前更改,每次计算f[j]时保证f[j-1]不变。
class Solution {
public:
int numDistinct(string s, string t) {
int n=t.size();
vector<int> f(n+1,0);
f[0]=1;
for(int i=0;i<s.size();++i)
for(int j=t.size()-1;j>=0;--j)
f[j+1]+=s[i]==t[j]?f[j]:0;
return f[n];
}
};