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 的子串 S(0-i)含有 T 的子串 T(0-j)的不同子串个数,状态
方程:
f[i][j] = f(i-1,j-1) + f(i-1,j) if t[i] = s[j]
f(i-1,j) if t[i] != s[j]
r | a | b | i | t | |
---|---|---|---|---|---|
r | 1 | ||||
a | 1 | 1 | |||
b | 1 | 1 | 1 | ||
b | 1 | 1 | 2 | 0 | |
b | 1 | 1 | 3 | 0 | 0 |
i | 1 | 1 | 3 | 3 | 0 |
t | 1 | 1 | 3 | 3 | 3 |
使用滚动数组+临时变量存储 f(i-1,j-1),可以优化空间复杂度到 O(n)
public class Solution {
public int numDistinct(String S, String T) {
int lenS = S.length();
int lenT = T.length();
if(lenT == 0 || lenS == 0 || lenS<lenT){
return 0;
}
int f[] = new int[lenT+1];
f[0] = 1;
for(int i = 0; i<lenS; i++){
for(int j=Math.min(i, lenT-1); j>=0; j--){
f[j+1] += (S.charAt(i) == T.charAt(j)? f[j]:0);
}
}
return f[lenT];
}
}