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

【LeetCode】Distinct Subsequences

时间:2014-07-12 13:37:37      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

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.

 

写了个深度优先的递归程序,TLE了。leetcode的要求真是高。。

空间换时间,用DP来做了,也就是说寻找一个递推条件,得出n-1到n步的关系。

把这个递推条件设为S前i个字符通过删除字符得到T前j个字符的转换方法,用二维数组元素transArr[i][j]记录。

(1)若S[i]==T[j],说明把S[i]、T[j]分别加入S[0~i-1]和T[0~j-1]可以完全复制transArr[i-1][j-1]种转换方式。另外,S[0~i-1]本身(无需加入S[i])也能以transArray[i-1][j]种方式转换为T[0~j]。

transArr[i][j] = transArr[i-1][j-1]+transArr[i-1][j];

(2)若S[i]!=T[j],说明S[i]无法用于转换为T[0~j],T[j]需要从S[0~i-1]中获取,因此S[0~i]与S[0~i-1]无异。

transArr[i][j] = transArr[i-1][j];

 

不过以上条件是不够的,transArr[m][n]结果将是0的累加.因此需要定义初始值。

transArray[i][0]设为1的含义是:任何长度的S,如果转换为空串,那就只有删除全部字符这1中方式。

 

class Solution 
{
public:
    int numDistinct(string S, string T) 
    {
        int m = S.size();
        int n = T.size();

        vector<vector<int>> transArr(m+1, vector<int>(n+1, 0));

        for(int i = 0; i < m+1; i ++)
            transArr[i][0] = 1;

        for(int i = 1; i < m+1; i ++)
        {
            for(int j = 1; j < n+1; j ++)
            {
                if(S[i-1] == T[j-1])
                    transArr[i][j] = transArr[i-1][j-1]+transArr[i-1][j];
                else
                    transArr[i][j] = transArr[i-1][j];
            }
        }

        return transArr[m][n];
    }
};

bubuko.com,布布扣

【LeetCode】Distinct Subsequences,布布扣,bubuko.com

【LeetCode】Distinct Subsequences

标签:style   blog   http   color   strong   os   

原文地址:http://www.cnblogs.com/ganganloveu/p/3836519.html

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