[LeetCode] 027: Distinct Subsequences
2017-09-10 20:48
561 查看
[Problem]
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
[Solution]
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.
[Solution]
class Solution { public: int numDistinct(string S, string T) { // Start typing your C/C++ solution below // DO NOT write int main() function // T is empty or S is empty if(T.size() == 0)return 1; if(S.size() == 0)return 0; // initial int **dp = new int*[T.size()+1]; for(int i = 0; i <= T.size(); ++i){ dp[i] = new int[S.size()+1]; } // dp for(int i = T.size(); i >= 0; --i){ for(int j = S.size(); j >= 0; --j){ // set the bottom-right one if(i == T.size() && j == S.size()){ dp[i][j] = 1; } else if(i == T.size()){ dp[i][j] = 0; } else if(j == S.size()){ dp[i][j] = 0; } // dp else{ if(T[i] != S[j]){ dp[i][j] = dp[i][j+1]; } else{ if(i == T.size()-1){ dp[i][j] = dp[i][j+1] + 1; } else{ dp[i][j] = dp[i][j+1] + dp[i+1][j+1]; } } } } } return dp[0][0]; } };说明:版权所有,转载请注明出处。Coder007的博客
相关文章推荐
- leetcode Distinct Subsequences DP
- LEETCODE: Distinct Subsequences
- LeetCode Distinct Subsequences(动态规划)
- leetcode之Distinct Subsequences
- leetcode Distinct Subsequences
- LeetCode Distinct Subsequences
- LeetCode Distinct Subsequences
- LeetCode(115) Distinct Subsequences
- LeetCode_115---Distinct Subsequences
- leetcode Distinct Subsequences
- leetcode第36题(distinct-subsequences)
- LeetCode之Distinct Subsequences
- [Leetcode] Distinct Subsequences *
- Leetcode: Distinct Subsequences
- LeetCode Distinct Subsequences
- [leetcode]Distinct Subsequences @ Python
- Distinct Subsequences leetcode
- leetcode:Distinct Subsequences
- LeetCode Distinct Subsequences
- Leetcode Distinct Subsequences 动态规划法活用总结