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.

看到这个题目的第一反应是,采用回溯法,列举S的所有有序子串,然后将子串与T 比较。结果 超时

class Solution {
public:
    int numDistinct(string S, string T) {
        int count=0;
        string aresult="";
        sub(S,T,aresult,count,0);
        return count;
        
    }
    void sub(string &s,string &t,string &aresult,int & count,int level){
        int n=s.length();
        if(level>n) return;
        if(aresult==t){
            count++;
            return;
        }
        for(int i=level;i<n;i++){
            aresult.push_back(s[i]);
            sub(s,t,aresult,count,i+1);
            aresult.pop_back();
        }
    }
};

之后,发现这个问题具有子结构特征,或许可以采用动态规划。发现动态规划的规律。

可以先尝试做一个二维的表int[][] Dis,用来记录匹配子序列的个数(以S="rabbbit",T = "rabbit"为例):

    r a b b b i t

  1 1 1 1 1 1 1 1

0 1 1 1 1 1 1 1

a 0 1 1 1 1

b 0 0 2 3 3 3

b 0 0 0 0 3 3 3

i 0 0 0 0 0 0 3 3

t 0 0 0 0 0 0 0 3  

从这个表可以看出,无论T的字符与S的字符是否匹配,Dis[i][j] = Dis[i][j - 1].就是说,假设S已经匹配了j - 1个字符,得到匹配个数为dp[i][j - 1].现在无论S[j]是不是和T[i]匹配,匹配的个数至少是dp[i][j - 1]。除此之外,当S[j]和T[i]相等时,我们可以让S[j]和T[i]匹配,然后让S[j - 1]和T[i - 1]去匹配。所以得到的递归为

 if(S[i]==T[j]) :Dis[i][j]=Dis[i-1][j-1]+Dis[i-1][j];  Dis[i-1][j]即选择将S[i]删去,而Dis[i-1][j-1]则保留
 else            :Dis[i][j]=Dis[i-1][j];      则S[i]没有任何作用,故为Dis[i-1][j]

class Solution {
public:
    int numDistinct(string S, string T) {
        int ns=S.length(),nt=T.length();
       // if(ns<nt) return 0;
        vector<vector<int>> Dis(ns+1,vector<int>(nt+1,0));
        for(int i=0;i<=ns;i++){
            Dis[i][0]=1;
        }
        for(int i=1;i<=ns;i++){
            for(int j=1;j<=nt;j++){
                if(S[i-1]==T[j-1]){
                    Dis[i][j]=Dis[i-1][j-1]+Dis[i-1][j]; 
                }
                else{
                    Dis[i][j]=Dis[i-1][j];
                }
            }
        }
        return Dis[ns][nt];
    }
    
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值