标签:distinct subsequence leetcode 动态规划 遍历
Distinct Subsequences
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,这样的去法有多少种。
动态规划,设dp[i][j]表示S前i个字符通过删除字符得到T前j个字符的转换方法,则
(1)若S[i]==T[j],说明把S[i]、T[j]分别加入S[0~i-1]和T[0~j-1]可以完全复制dp[i-1][j-1]种转换方式。另外,S[0~i-1]本身(无需加入S[i])也能以dp[i-1][j]种方式转换为T[0~j],当然可能有0种,比如S[0~i-1]中根本不包含T[j],但由于i >= j,所有S[0~i-1]可能包含T[0~j],所以有
dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
(2)若S[i]!=T[j],说明S[i]无法用于转换为T[0~j],所以把S[i]加入进行转换的方法和不加入是重复的,所以T[j]需要从S[0~i-1]中获取,因此S[0~i]与S[0~i-1]无异,即dp[i][j] = dp[i-1][j];
初始化为:dp[i][0]设为1,即任何长度的S,如果转换为空串,那就只有删除全部字符这1中方式。
具体代码如下:
class Solution { public: int numDistinct(string S, string T) { int length1 = S.size(),length2 = T.size(),i,j; vector< vector<int> > dp(length1+1); for (i = 0;i <= length1;++i) { vector<int> tmp(length2+1,0); dp[i] = tmp; } for (i = 0;i <= length1;i++)dp[i][0] = 1;//初始化 for (i = 1;i <= length1;i++) { for (j = 1;j <= length2;j++) { if(S[i-1] == T[j-1])dp[i][j] = dp[i-1][j-1] + dp[i-1][j]; else dp[i][j] = dp[i-1][j]; } } return dp[length1][length2]; } };
leetcode 之 Distinct Subsequences
标签:distinct subsequence leetcode 动态规划 遍历
原文地址:http://blog.csdn.net/fangjian1204/article/details/39104085