[LeetCode] 027: Distinct Subsequences

来源:互联网 发布:js隐藏菜单栏 编辑:程序博客网 时间:2024/06/05 15:48
[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, "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的博客
原创粉丝点击