您的位置:首页 > 产品设计 > UI/UE

[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,
"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的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: