leetcode: Distinct Subsequences
2014-09-03 00:01
507 查看
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,
a subsequence of
not).
Here is an example:
S =
Return
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.
class Solution { public: int numDistinct(string S, string T) { if (S.size() == 0 || T.size() == 0) return 0; int m = S.size(); int n = T.size(); vector<vector<int> > auxVtr(n+1, vector<int>(m+1)); for (int i=0; i<=n; i++) { for (int j=0; j<=m; j++) { auxVtr[i][j] = 0; } } // "" substring is also the subset of S for (int j=0; j<=m; j++) auxVtr[0][j] = 1; for (int i=1; i<=n; i++) { for (int j=1; j<=m; j++) { /* * to understand this logic * for example S=ABCC; T=BC * When compare to S's last character 'C' * a(S'=ABC T'=B aux = 1) b(S"=ABC T"=BC aux = 1) * if S' last character is not 'C', the result would be b * but now, S' last character is 'C', b is the same as above, but we need add a in this scenario */ if (T[i-1] == S[j-1]) { auxVtr[i][j] = auxVtr[i-1][j-1]+auxVtr[i][j-1]; } else { auxVtr[i][j] = auxVtr[i][j-1]; } } } return auxVtr [m]; } };
相关文章推荐
- Leetcode: Distinct Subsequences
- leetcode distinct subsequences
- LeetCode:Distinct Subsequences
- Leetcode: Distinct Subsequences
- Leetcode Distinct Subsequences Java
- 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 *
- leetcode Distinct Subsequences
- (leetcode)Distinct Subsequences
- LeetCode Distinct Subsequences
- LeetCode: Distinct Subsequences
- [leetcode]Distinct Subsequences @ Python
- LeetCode:Distinct Subsequences