问题描述:
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(S,T) = f(S-1,T-1)+f(S-1,T) (当S的最后一个字符和T的最后字符相同)
f(S,T) = f(S-1,T) (当S的最后一个字符和T的最后一个字符不同)
代码:
public int numDistinct(String S, String T) { //java
if(S.length() < T.length())
return 0;
int sizeS = S.length();
int sizeT = T.length();
if(sizeS == sizeT)
{
if(S.equals(T))
return 1;
else return 0;
}
if(sizeT == 0)
return 1;
int [][] array = new int[sizeS+1][sizeT];
for(int i = 0; i < sizeT; i++)
array[0][i] = 0;
char fch = T.charAt(0);
for(int i = 1; i <=sizeS; i++)
{
if(fch == S.charAt(i-1))
array[i][0] = array[i-1][0]+1;
else array[i][0] = array[i-1][0];
}
for(int i = 1; i <=sizeS; i++)
{
char sch = S.charAt(i-1);
for(int j = 1; j <sizeT; j++)
{
char tch = T.charAt(j);
if(tch == sch)
array[i][j] = array[i-1][j-1]+array[i-1][j];
else array[i][j] = array[i-1][j];
}
}
return array[sizeS][sizeT-1];
}