【LeetCode】Distinct Subsequences

来源:互联网 发布:哈长城市群知乎 编辑:程序博客网 时间:2024/04/25 15:41

参考链接

http://blog.csdn.net/xshalk/article/details/8223120

http://blog.csdn.net/bigapplestar/article/details/17523391

http://blog.csdn.net/jellyyin/article/details/9060709

题目描述

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.


题目分析

题意:

给定2个字符串a, b,求b在a中出现的次数。要求可以是不连续的,但是b在a中的顺序必须和b以前的一致。

示例说明:
S = "rabbbit"T = "rabbit"
为了区分3个b,我们写作b0b1b3
T在S中出现了3分。分别是rab0b1it,rab0b2it,rab1b2it


思路:动态规划的关键就是找递归公式。

类似于数字分解的题目。dp[i][j]表示:b的前j个字符在a的前i个字符中出现的次数。

如果a[i] == b[j]则 dp[i][j] = dp[i-1][j] + dp[i-1][j-1]

如果a[i] != b[j]则 dp[i][j] = dp[i-1][j]


总结

这个一个典型的动态规划题,需要多多复习。

代码示例

推荐学习C++的资料

C++标准函数库
http://download.csdn.net/detail/chinasnowwolf/7108919
在线C++API查询
http://www.cplusplus.com/


0 0
原创粉丝点击