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

leetcode之Distinct Subsequences

2014-07-29 17:33 316 查看
题目大意:

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
.

意思就是:

给定字符串S和T, 求得在S中字串T的数目.

做题思路:

动态规划(DP).和最长公共子序列有点类似.

解题方法是: 设record[i][j] 表示S到第i个字符串, T到第j个字符串为止, 重复字串的数目. 则可分两种情况:

当S[i] == T[j], 则record[i][j] = record[i-1][j-1] + record[i-1][j];

当S[i] != T[j], 则record[i][j] = record[i-1][j];

代码如下:

class Solution {

public:

int numDistinct(string S, string T) {

string::size_type lenghtS = S.size();

if(lenghtS == 0){

return 0;

}

string::size_type lenghtT = T.size();

if(lenghtS == 1){

if(lenghtT == 1 && S[0] == T[0]){

return 1;

}

else{

return 0;

}

}

int record[lenghtS+1][lenghtT+1];

memset(record, 0, sizeof(int)*(lenghtS+1)*(lenghtT+1));

for(int i=0;i<lenghtS+1;i++){

record[i][0] = 1;

}

for(int i=1;i<lenghtS+1;i++){

for(int j=1;j<lenghtT+1;j++){

record[i][j] = (S[i-1] == T[j-1]?record[i-1][j-1] + record[i-1][j]:record[i-1][j]);

}

}

return record[lenghtS][lenghtT];

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: