首页 > 代码库 > Distinct Subsequences
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
.
首先考虑动态规划,最初的想法是用矩阵grid[i][j]记录S[i]是否能与T[j]匹配,然后从右下角开始找,每步只能向左或者左上走,统计有多少条路可以到达左上角,但是发现会有问题,无法找到rabbbit这条路线(红色表示去掉的)。重新考虑状态方程,将grid[i][j]表示S(0,i)中T(0,j)出现的次数,首先,无论S[i]和T[j]是否相等,若不使用S[i],则grid[i][j] = grid[i-1][j];若S[i]==T[j],则可以使用S[i],则有grid[i][j] = grid[i-1][j]+grid[i-1][j-1]。这样使用了m*n的额外空间。由状态方程可以看出,第i行上的元素只与i-1行有关,则可以只记录本行和上一行的状态,之前的可以抛弃,这样,将空间复杂度降低到了O(n)。时间复杂度为O(m*n)。
代码如下:
1 public int numDistinct(String S, String T) { 2 int grid[] = new int[T.length()+1]; 3 grid[0] = 1; 4 for (int i = 0; i < S.length(); ++i) { 5 for (int j = T.length() - 1; j >= 0; --j) { 6 grid[j + 1] += S.charAt(i) == T.charAt(j) ? grid[j] : 0; 7 } 8 } 9 return grid[T.length()]; 10 }