题目描述
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"
Return3.
设subs[i][j]表示S[1~i]里有subs[i][j]种删除完字符之后为T[1~j]的方法。
则递推关系式:
1)如果S[i+1] == T[j + 1],两种选择:删除S[i + 1],则种类数为S[1~i]与T[1~j+1]的方法种类数;保留S[i+1],则方法种类数为 S[1~i]与T[1~j]的种类数。
2)如果S[i+1] != T[j + 1],只能删除S[i+1],看S[1~i]与T[1~j]之间的种类数。
实现递推代码如下:
public class Solution {
public int numDistinct(String S, String T) {
if(S.equals(""))
return 0;
if(T.equals(""))
return 1;
int lenS = S.length() + 1;
int lenT = T.length() + 1;
int [][] subs = new int [lenS][lenT];
for(int i = 0; i < lenS; ++i)
subs[i][0] = 1;
for(int k = 1; k < lenT; ++k){
for(int i = 1; i < lenS; ++i){
if(T.charAt(k - 1) == S.charAt(i - 1)){
subs[i][k] = subs[i - 1][k] + subs[i - 1][k - 1];
}else{
subs[i][k] = subs[i - 1][k];
}
}
}
return subs[lenS - 1][lenT - 1];
}
}