題目描述:
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
.
參考答案1:
利用遞歸的思路。假設當前輸入串分別爲 s_tmp, t_tmp, 目的是求s_tmp的不同子序列中t_tmp出現的個數。先利用for循環尋找s_tmp串中第一個與t_tmp[0]對應的字符,從而確定了輸入遞歸函數的新的s_tmp,t_tmp。
不過這種方法在LeetCode上會TLE, 僅供參考。
class Solution {
public:
int numDistinct(string s, string t) {
if(s.size() < t.size()) return 0;
if(t.size() == 0) return 1;
int num = 0;//可能數
for(int i = 0;i < s.size();i++)//尋找初始對應點,有可能是多個
{
if(s[i] == t[0])//i開始對應
{
string s_tmp = s.substr(i+1);
string t_tmp = t.substr(1);
num += numDistinct(s_tmp, t_tmp);
}
}
return num;
}
};
參考答案2:
利用DP動態規劃的思路。定義table[i][j]爲s[0:i]的不同子序列中t[0:j]出現的個數,那麼按照如下方式構建table表:
初始化:table[i][0] = 1,for i ∈ [0,s.size())
如果 s[i] != t[j]: table[i][j] = table[i - 1][j];
如果 s[i] == t[j]: 分s[i]與t[j]是否配對兩種情況,則 table[i][j] = table[i-1][j] + table[i-1][j-1]
int numDistinct(string s, string t) {
if(s.size() < t.size()) return 0;
if(t.size() == 0) return 1;
int const M = s.size();
int const N = t.size();
vector<vector<int>> table(M + 1,vector<int>(N + 1,0));
for(int i = 0;i < M;i++)
{
table[i][0] = 1;
}
for(int i = 0;i < M ;i++)
{
for(int j = 0;j < N ;j++)
{
if(s[i] == t[j])
{
table[i+1][j+1] = table[i][j+1] + table[i][j];
}
else
{
table[i+1][j+1] = table[i][j+1];
}
}
}
return table[M][N];
}