【一天一道LeetCode】#115. Distinct Subsequences

来源:互联网 发布:de beers 知乎 编辑:程序博客网 时间:2024/06/03 13:25

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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.

(二)解题

题目大意:给定字符串T和S,求S的子串中有多少与T相等。

解题思路:S的子串代表在S中删除一些字符组成的字符串,那么可以很容易想到用递归来解决。
如果当前s[i]==s[j],有两种情况,选择该字母(i++,j++)和跳过该字母(i++)
如果s[i]!=s[j],则直接i++.
具体见代码:

class Solution {public:    int numDistinct(string s, string t) {        if(s.length()==0||t.length()==0) return 0;        int num =0;        dpDistinct(s,t,0,0,num);        return num;    }    void dpDistinct(string& s, string& t , int i , int j,int& num)    {        if(j==t.length()){num++;return;}        if(s[i]==t[j])        {            //choose this words            if(i<s.length()&&j<t.length()) dpDistinct(s, t , i+1, j+1,num);            //not choose this words            if(i<s.length()) dpDistinct(s, t , i+1, j,num);        }        else             //Don't equal            if(i<s.length()) dpDistinct(s, t , i+1, j,num);    }};

然后……直接超时了。

观察上述代码,发现有很多重复的判断,因此,可以采用动态规划的思想。

开始找状态转移方程。dp[i][j]用来表示s中j之前的子串subs中有多少个不同的subt,其中subt为t中i之前的字符组成的子串。

首先,初始化dp,令dp[0][j]都等于1,因为s中删除所有的字符都能组成空串。

如果t[i] == s[j],那么dp[i][j] = dp[i][j-1]+dp[i-1][j-1]

否则,dp[i][j] = dp[i][j-1]

举例说明一下:s为abbbc,t为abc

dp 空 a b b b c 空 1 1 1 1 1 1 a 0 1 1 1 1 1 b 0 0 1 2 3 3 c 0 0 0 0 0 3

具体解释看代码:

class Solution {public:    int numDistinct(string s, string t) {        vector<vector<int>> dp;        for(int i = 0 ; i < t.length()+1;i++)        {            vector<int> temp(s.length()+1,0);            dp.push_back(temp);        }        for(int i = 0 ; i < s.length()+1;i++) dp[0][i]=1;//初始化dp        for(int i = 1 ; i < t.length()+1; i++)        {            for(int j = 1 ; j < s.length()+1 ; j++)            {                if(s[j-1]==t[i-1])                {                    dp[i][j] = dp[i-1][j-1]+dp[i][j-1];//状态转移方程                }                else                     dp[i][j] = dp[i][j-1];            }        }        return dp[t.length()][s.length()];//返回    }};
0 0