LeetCode(115) Distinct Subsequences
来源:互联网 发布:呢大衣起球 知乎 编辑:程序博客网 时间:2024/05/16 12:19
题目如下:
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 ="rabbbit",T = "rabbit"为例):
dp[i][j]表示T的从0开始长度为i的子串和S的从0开始长度为j的子串的匹配的个数。
比如, dp[2][3]表示T中的ra和S中的rab的匹配情况。
(1)显然,至少有dp[i][j] = dp[i][j - 1].
比如, 因为T 中的"ra" 匹配S中的 "ra", 所以dp[2][2] = 1 。 显然T 中的"ra" 也匹配S中的 "rab",所以s[2][3] 至少可以等于dp[2][2]。
(2) 如果T[i-1] == S[j-1], 那么dp[i][j] = dp[i][j - 1] + (T[i - 1] == S[j - 1] ? dp[i - 1][j - 1] : 0);
比如, T中的"rab"和S中的"rab"显然匹配,
根据(1), T中的"rab"显然匹配S中的“rabb”,所以dp[3][4] = dp[3][3] = 1,
根据(2), T中的"rab"中的b等于S中的"rab1b2"中的b2, 所以要把T中的"rab"和S中的"rab1"的匹配个数累加到当前的dp[3][4]中。 所以dp[3][4] += dp[2][3] = 2;
(3) 初始情况是
dp[0][0] = 1; // T和S都是空串.
dp[0][1 ... S.length() ] = 1; // T是空串,S只有一种子序列匹配。
dp[1 ... T.length() ][0] = 0; // S是空串,T不是空串,S没有子序列匹配。
我的代码:
//37msclass Solution {public: int numDistinct(string S, string T) { vector<vector<int> > dp(T.length() + 1, vector<int>(S.length() + 1, 0)); dp[0][0] = 1; for (int i = 1; i < S.length() + 1; ++i) dp[0][i] = 1; for (int i = 1; i < T.length() + 1; ++i) dp[i][0] = 0; for (int i = 1; i < T.length() + 1; ++i) { for (int j = 1; j < S.length() + 1; ++j) { dp[i][j] = dp[i][j - 1]; if (S[j - 1] == T[i - 1]) dp[i][j] += dp[i - 1][j - 1]; } } return dp[T.length()][S.length()]; }};
小结扩展:
创建二维vector数组并初始化
vector<vector <int> > ivec(m ,vector<int>(n,0));
创建二维数据,初始化为m个空数组。
vector<vector <int> > ivec(m);
参考资料:
http://blog.csdn.net/abcbc/article/details/8978146
- LeetCode: Distinct Subsequences [115]
- LeetCode 115 Distinct Subsequences
- [leetcode 115] Distinct Subsequences
- LeetCode(115) Distinct Subsequences
- leetcode || 115、Distinct Subsequences
- Distinct Subsequences leetcode 115
- leetcode 115: Distinct Subsequences
- LeetCode 115: Distinct Subsequences
- leetcode-115-Distinct Subsequences
- LeetCode 115、Distinct Subsequences
- LeetCode 115、Distinct Subsequences
- LeetCode 115、Distinct Subsequences
- Leetcode 115 Distinct Subsequences
- LeetCode 115 Distinct Subsequences
- LeetCode 115 Distinct Subsequences
- Leetcode 115 Distinct Subsequences
- [leetcode-115]Distinct Subsequences(java)
- LeetCode(115) Distinct Subsequences
- 美国联邦政府使用下面的这些规划计算1995年每个公民的 个人收入所得税
- android4.0以上网络访问为什么要开线程,已经Handler的使用
- Android studio at ubuntu 14.04, run ADB error:没有那个文件或目录
- start
- sql where 1=1和 0=1 的作用
- LeetCode(115) Distinct Subsequences
- 第3章 习题3.12 合并文件
- Get the page name in asp.net web page
- 解析国足末战:上下半场如两队 国足锁定世预赛种子队
- 您好,欢迎分享关于携程网站的使用感受和功能建议!
- HDU 4405 Aeroplane chess(期望DP)
- Guava学习笔记-Function,Predicate
- 能够使自己的优化水平,有一定性晋升。
- Windows下利用Cygwin登录远程Linux