[leetcode] 115. Distinct Subsequences 解题报告

来源:互联网 发布:seo能自学吗 编辑:程序博客网 时间:2024/04/30 03:52

题目链接:https://leetcode.com/problems/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,删除S中的一些字符,能得到几个和T相同的子串,例如:S = "rabbbit"T = "rabbit"

删除S的第一个b,第二个b,第三个b得到三个子串,这三个子串都和T相等,因此可以答案是3.

可以用一个二维数组来记录子状态,dp[i][j]代表在S[0, j-1]中有dp[i][j]个子串和T[0, i-1]相等,接着分析如何把问题转化为子问题。

分两种情况:

1. 如果 T[i] != S[j],则很容易理解dp[i][j] = dp[i][j-1],即如果当前的字符不相等,则dp[i][j]的值为S[0, j-1]去掉当前不匹配的这个字符的子串包含几个T[0, i-1]的子序列

    即dp[i][j] = dp[i][j-1];

2. 如果T[i] = S[j], 那么dp[i][j]就可以继承dp[i-1][j-1]的值,再加上没有s[j-1]这个字符的值

    即如果T[i] = S[j],则dp[i][j] = dp[i-1][j-1] + dp[i][j-1];

另外初始状态为dp[i][0] = 0, dp[0][j] = 1, 可以理解为如果T为空串,则为1,因为空串是任意字符串的子串。如果S为空,那么为0,因为空串不能包含一个非空字符串。

时间复杂度为O(M*N), 空间复杂度为O(M*N),具体代码如下:

class Solution {public:    int numDistinct(string s, string t) {        int len1 = s.size(), len2 = t.size();        vector<vector<int>> dp(len2+1, vector<int>(len1+1, 0));        for(int i = 0; i < len1; i++) dp[0][i] = 1;        for(int i = 1; i <= len2; i++)        {            for(int j = 1; j <= len1; j++)            {                dp[i][j] = dp[i][j-1];                if(t[i-1] == s[j-1]) dp[i][j] += dp[i-1][j-1];            }        }        return dp[len2][len1];    }};


0 0