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 子串的个数,想当然就想到了递归的解法:每层递归比较S[i]、T[j],如果 S[i]、T[j] 相等递归求解S[i+1]、T[j+1] 和 S[i+1]、T[j](有可能 S 中有多个等于 T[j] 的字符),如果 S[i]、T[j] 不相等递归求解 S[i+1]、T[j],如果递归出口为递归到 S 结尾或 T 结尾,如果递归到 T 结尾,最终结果+1;

代码如下:

class Solution {
public:
    int numDistinct(string s, string t) {
		if(t.size() > s.size())
			return 0;
		int count = 0;
		countSubStr(s, t, 0, 0, &count);
		return count;
    }
	void countSubStr(string& s, string& t, int sk, int tk, int* count)
	{
		if(sk == s.size() || tk == t.size())
		{
			if(tk == t.size())
				(*count)++;
			return;
		}
		if(s[sk] == t[tk])
		{
			countSubStr(s, t, sk+1, tk+1, count);
			countSubStr(s, t, sk+1, tk, count);
		}
		else
			countSubStr(s, t, sk+1, tk, count);
	}
};
不幸超时,处理字符串的递归一般都超时,那就只能动态规划解决了。

此题为二维动态规划,构建 T.len * S.len 的二维数组 F ,初始化为0;F[i][j] 代表T[0]~T[i] 在 S[0]~[j]的子串个数

初始化 F[0][j],即 T 的第一个字符与 S 的匹配情况,如果 T[0] == S[j] 则 F[0][j] = 1,T[0] 后面的字符匹配均要根据 T 中上一字符的匹配情况而定,匹配到 T[i] 和 S[j] 时,如果两个字符相等,那么F[i][j] 为 F[i-1][1]、F[i-1][2]、...、F[i-1][j-1] 的和,(可以画二维图理解)

公式如下:

F[i-1][1]+F[i-1][2]+...+F[i-1][j-1] ; (T[i] == S[j])

F[i][j] = {

0; (T[i] != S[j])

代码如下:

class Solution {
public:
    int numDistinct(string s, string t) {
		if(t.size() > s.size())
			return 0;
		int slen = s.length(), tlen = t.length();
		int result = 0;
		vector<vector<int> > F(tlen, vector<int>(slen, 0));
		for(int j=0; j<slen; ++j)
			if(t[0] == s[j])
				F[0][j] = 1;
		for(int i=1; i<tlen; ++i)
		{
			for(int j=1; j<slen; ++j)
			{
				if(t[i] == s[j])
				{
					for(int h=0; h<j; ++h)
						F[i][j] += F[i-1][h];
				}
			}
		}
		for(int j=0; j<slen; ++j)
			result += F[tlen-1][j];
		return result;
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值