码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Distinct Subsequences

时间:2015-01-05 21:58:33      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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

[leetcode]Distinct Subsequences

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/42432419

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!