LeetCode: Distinct Subsequences
2014-08-26 22:24
429 查看
[b]LeetCode: Distinct Subsequences[/b]
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,
Here is an example:
S =
Return
地址:https://oj.leetcode.com/problems/distinct-subsequences/
算法:这道题的题目描述的不是很清楚。按照题目给出的例子,应该是在S中寻找等于T的子序列,然后求这样的子序列的个数。我是用动态规划解决的,用二维dp来存储子问题的解,其中dp[i][j]表示子问题(T[0~i],S[0~j])的解,这样我们就可以按行优先来完成各个子问题,其中如果T[i]==S[j],那么dp[i][j]=dp[i][j-1] + dp[i-1][j-1];否则,dp[i][j]=dp[i][j-1]。其中第一行跟第一列都可以实现初始化。代码:
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.
地址:https://oj.leetcode.com/problems/distinct-subsequences/
算法:这道题的题目描述的不是很清楚。按照题目给出的例子,应该是在S中寻找等于T的子序列,然后求这样的子序列的个数。我是用动态规划解决的,用二维dp来存储子问题的解,其中dp[i][j]表示子问题(T[0~i],S[0~j])的解,这样我们就可以按行优先来完成各个子问题,其中如果T[i]==S[j],那么dp[i][j]=dp[i][j-1] + dp[i-1][j-1];否则,dp[i][j]=dp[i][j-1]。其中第一行跟第一列都可以实现初始化。代码:
class Solution { public: int numDistinct(string S, string T) { if (S.empty() || T.empty()){ return 0; } int len_S = S.size(); int len_T = T.size(); vector<int> temp(len_S); vector<vector<int> > dp(len_T,temp); if(T[0] == S[0]) dp[0][0] = 1; else dp[0][0] = 0; for(int i = 1; i < len_S; ++i){ if(T[0] == S[i]){ dp[0][i] = dp[0][i-1] + 1; }else{ dp[0][i] = dp[0][i-1]; } } for(int i = 1; i < len_T; ++i){ dp[i][0] = 0; } for(int i = 1; i < len_T; ++i){ for(int j = 1; j < len_S; ++j){ if(T[i] != S[j]){ dp[i][j] = dp[i][j-1]; }else{ dp[i][j] = dp[i][j-1] + dp[i-1][j-1]; } } } return dp[len_T-1][len_S-1]; } };
相关文章推荐
- LeetCode Distinct Subsequences
- LeetCode: Distinct Subsequences [115]
- Leetcode: Distinct Subsequences
- LeetCode(115) Distinct Subsequences
- Leetcode dp Distinct Subsequences
- LEETCODE: Distinct Subsequences
- leetcode Distinct Subsequences
- LeetCode Distinct Subsequences
- Leetcode -- Distinct Subsequences
- LeetCode: Distinct Subsequences
- LeetCode题解:Distinct Subsequences
- Leetcode Distinct Subsequences
- Leetcode Distinct Subsequences 动态规划法活用总结
- leetcode distinct subsequences dp solution
- Leetcode:Distinct Subsequences
- leetcode: Distinct Subsequences
- leetcode 之 Distinct Subsequences
- #leetcode#Distinct Subsequences
- leetcode第36题(distinct-subsequences)
- **Leetcode_distinct-subsequences