[leetcode]Distinct Subsequences

问题描述:

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];
    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值