问题描述:
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
.
问题分析:
只可以用删除字符的方法从第一个字符串变换到第二个字符串,求出一共有多少种变换方法。做多了就发现,又是一个动态规划的题。那就直接上二维数组d[][]:
dp[i][j]表示:T的前j个字符在S的前i个字符中出现的次数。
public int numDistinct(String S, String T) {
if(S==null||T==null||S.length()<=0){
return 0;
}
if(T.length()<=0)
return 1;
int slen = S.length();
int tlen = T.length();
int dp[][]=new int[slen+1][tlen+1];
//边界初始化
for(int i=0;i<=tlen;i++){
dp[0][i]=0;
}
for(int i=0;i<=slen;i++){
dp[i][0]=1;
}
for(int i=1;i<=slen;i++){
for(int j=1;j<=tlen;j++){
//不等情况
if(S.charAt(i-1) != T.charAt(j-1)){
dp[i][j]=dp[i-1][j];
}else{
//相等情况
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
}
return dp[slen][tlen];
}