[LeetCode] 027: Distinct Subsequences
来源:互联网 发布:js隐藏菜单栏 编辑:程序博客网 时间:2024/06/05 15:48
[Problem]
[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 {说明:版权所有,转载请注明出处。Coder007的博客
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];
}
};
阅读全文
0 0
- [LeetCode] 027: Distinct Subsequences
- LeetCode Distinct Subsequences
- [LeetCode]Distinct Subsequences
- [Leetcode] Distinct Subsequences *
- [leetcode] Distinct Subsequences
- [LeetCode] Distinct Subsequences
- [Leetcode] Distinct Subsequences
- leetcode 111: 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] 023: Convert Sorted Array to Binary Search Tree
- [LeetCode] 024: Convert Sorted List to Binary Search Tree
- LeetCode:M-19. Remove Nth Node From End of List
- [LeetCode] 025: Count and Say
- [LeetCode] 026: Decode Ways
- [LeetCode] 027: Distinct Subsequences
- Activity的那些事
- [LeetCode] 028: Divide Two Integers
- [LeetCode] 029: Edit Distance
- asynctask_httpclient
- [LeetCode] 030: First Missing Positive
- Makefile---$@ $^ $<
- [LeetCode] 031: Flatten Binary Tree to Linked List
- c#修改程序名称——转载