Description
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).
Given S = "rabbbit"
, T = "rabbit"
, return 3
.
动态规划题
我的思路过程:先定义一个boolean的二维数组,然后画出二维数组图找公式,最后 在根据二维数组中的true和false来计算个数。开始的时候我是想用int代替boolean.可是用了int只有不知道怎么加 才能直接得到 个数。所以用boolean。在根据二维数组计算的时候,发现一条规律。
例如 S中有连续的n个a. 设n=5
若T中有1个a, 则 有5种方式。
若T中有2个相邻的a,则有4+3+2+1种
若T中有3个相邻的a,则有(3+2+1)+(2+1)+1中,
如图:
看到这个图 突然发现(也就是脑子灵光一闪)当T中有2个相邻的a时,a[2][1]=a[1][1] +a[1][0] 类推 a[4][1] =a[3][1]+a[3][0].这样我就 很开心了,利用这个规律 可以将boolean换位int,然后得到公式。(虽然时间漫长 。。但是有曙光 可是我还是没有推导出来。。。)
最后 搜索一下,别人的思路:
(空白 代表是0)创建一个二维数组int[][] temp,用来记录匹配子序列的个数.
当T中字符和S中字符相等的时候 temp[i][j]=temp[i-1][j]+temp[i-1][j-1],不等,temp[i][j]=temp[i-1][j-1];
public int numDistinct(String S,String T){
int[][] temp=new int[S.length()+1][T.length()+1];
for(int j=0;j<temp[0].length;j++){
temp[0][j]=0;
}
for(int i=0;i<temp.length;i++){
temp[i][0]=1;
}
for(int i=1;i<=S.length();i++){
for(int j=1;j<=T.length();j++){
System.out.println( i+" "+j+" "+T.charAt(j-1) +" "+S.charAt(i-1));
/*if(T.charAt(j-1) == S.charAt(i-1)){
temp[i][j]=temp[i-1][j]+temp[i-1][j-1];
}else{
temp[i][j]=temp[i-1][j];
}*/
temp[i][j]=T.charAt(j-1) == S.charAt(i-1)?(temp[i-1][j]+temp[i-1][j-1]):temp[i-1][j];
}
}
return temp[S.length()][T.length()];
}
参考网址:http://blog.csdn.net/abcbc/article/details/8978146