[LeetCode]Distinct Subsequences

本文介绍了一种计算字符串S中不同子序列与目标字符串T相匹配数量的算法。通过动态规划的方法,在一维或二维数组中记录中间结果,避免了重复计算,提高了效率。

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

class Solution {
//dp
//Let f(i, j) to be the number of distinct subsequences of T(j:) in S(i:). Consider the ith character in S. If we can use it to match T[j], namely S[i] == T[j], then
//1. f(i, j) = f(i+1, j+1).
//If we do not want use it in our matching, then
//2. f(i, j) = f(i+1, j). because every T[j] must be matched
//Thus,f(i, j) = f(i+1, j) + (S[i] == T[j]) * f(i+1, j+1).

// some tricks
//1. decompose it to dimension 1, and so i:(n,0]
//2. for the same j, we can not let T[j] affect f(i+1, j+1) then through f(i+1, j+1) affect f(i+1, j),  so j:[0,n)
public:
    int numDistinct(string S, string T) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		vector<int> f(T.size()+1, 0);
		f[T.size()] = 1;
        for(int i = S.size()-1; i >= 0; i--)
		{//decompose to one dimension
			for(int j = 0; j < T.size(); ++j)
			{
				f[j] = f[j]+(S[i]==T[j])*f[j+1];
			}
		}
		//
		return f[0];
    }
};

second time

class Solution {
public:
    int numDistinct(string S, string T) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int len1 = S.size();
        int len2 = T.size();
        vector<vector<int> > f(len1+1, vector<int>(len2+1, 0));
        for(int i = 0; i <= len1; ++i) f[i][0] = 1;
        for(int i = 1; i <= len1; ++i)
        {
            for(int j = 1; j <= len2; ++j)
            {
                f[i][j] += f[i-1][j];
                if(S[i-1] == T[j-1]) f[i][j] += f[i-1][j-1];
            }
        }
        return f[len1][len2];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值