Distinct Subsequences--lintcode

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).

Example

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值