[LeetCode] Distinct Subsequences [29]
Posted zhchoutai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Distinct Subsequences [29]相关的知识,希望对你有一定的参考价值。
题目
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。问一共能有多少种删除方法?
这个题用常规方法超时。
得用动态规划,动态规划最基本的就是要找到动态规划方程。
首先记:dp[i][j] 为 从S[0..j-1]中删除某些字符后得 T[0...i-1]的不同删除方法数量。
动态规划方程为: dp[i][j] = dp[i][j-1] + (S[j-1]==T[i-1] ? dp[i-1][j-1] : 0);
代码实现
class Solution { public: int numDistinct(string S, string T) { int m = S.size(); int n = T.size(); if(m<n) return 0; vector<vector<int> > dp(n+1, vector<int>(m+1, 0)); for(int i=0; i<m; ++i) dp[0][i] = 1; for(int i=1; i<=n; ++i){ for(int j=1; j<=m; ++j){ dp[i][j] = dp[i][j-1] + (S[j-1]==T[i-1] ? dp[i-1][j-1] : 0); } } return dp[n][m]; } };
对于辅助数组我们其有用到的也仅仅有当前行和其前一行。所以我们能够仅仅申请两行的辅助数组。优化代码例如以下:
class Solution { public: int numDistinct(string S, string T) { int m = S.size(); int n = T.size(); if(m<n) return 0; vector<int> dp1(m+1, 1); vector<int> dp2(m+1, 0); for(int i=1; i<=n; ++i){ for(int j=1; j<=m; ++j){ dp2[j] = dp2[j-1] + (S[j-1]==T[i-1] ? dp1[j-1] : 0); } dp1.clear(); dp1 = dp2; dp2[0] = 0; } return dp1[m]; } };
另外。我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
以上是关于[LeetCode] Distinct Subsequences [29]的主要内容,如果未能解决你的问题,请参考以下文章
[动态规划] leetcode 115 Distinct Subsequences
LeetCode Distinct Subsequences
[LeetCode]Distinct Subsequences,解题报告
[LeetCode]Distinct Subsequences,解题报告