[leetcode] 115. Distinct Subsequences 解题报告

本文介绍了一种使用动态规划解决LeetCode第32题的方法,该题要求计算字符串S中有多少个不同的子序列与字符串T相同。通过分析问题并建立状态转移方程,给出了具体的实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: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];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值