前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 115 Distinct Subsequences

LeetCode 115 Distinct Subsequences

作者头像
ShenduCC
发布2018-07-24 16:02:39
5880
发布2018-07-24 16:02:39
举报
文章被收录于专栏:算法修养

Pick One


Given a string S and a string T, count the number of distinct subsequences of S which equals T.

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 1:

代码语言:javascript
复制
Input: S = "rabbbit", T = "rabbit"
Output: 3
Explanation:

As shown below, there are 3 ways you can generate "rabbit" from S.
(The caret symbol ^ means the chosen letters)

rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^

Example 2:

代码语言:javascript
复制
Input: S = "babgbag", T = "bag"
Output: 5
Explanation:

As shown below, there are 5 ways you can generate "bag" from S.
(The caret symbol ^ means the chosen letters)

babgbag
^^ ^
babgbag
^^    ^
babgbag
^    ^^
babgbag
  ^  ^^
babgbag
    ^^^

第一到hard难度的题
其实也是一道水题,
首先我用了暴力深搜,果然超时,效率是(最差情况)s的长度:n,t的长度:m

O(n) = n*(n-1)*(n-2)*...(n-m+1)*m

正确的解法应该是前缀和,
遍历t字符串中的每个字符ti 找到ti 在s字符串中的位置si,统计si的前缀和sss,这里的前缀和是值si前面有多少个满足的条件的t的前缀字符串,
O(n)=  n * m

c++
代码语言:javascript
复制
class Solution {
public:
    int result;
    int sss[100005];//ss数组的前缀和数组
    int ss[100005];//当前字符串前面满足条件的前缀字符串的个数
    int numDistinct(string s, string t) {
        int lens = s.length();
        int lent = t.length();
        memset(sss,0,sizeof(sss));
      
        for(int j=0;j<lent;j++)
        {
            memset(ss,0,sizeof(ss));
            for(int i=j;i<lens;i++)
            {
                if(s[i]==t[j])
                {
                    ss[i]=(j==0?1:sss[i-1]);
                }
            }
            for(int i=0;i<lens;i++)
            {
                if(i==0){sss[i]=ss[i];continue;}
                sss[i]=sss[i-1]+ss[i];
            }
        }
        for(int i=0;i<lens;i++)
        {
            result += ss[i];
        }
        return result;
    }
    
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-07-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档