leetcode -day 15 Distinct Subsequences
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
.
分析:此題乍一看看不明確啥意思,後面慢慢理解。就是說T是S的子串,這裡的子串是說原字串刪除某些字元後剩餘字元的組合,題目是S中通過刪除操作獲得子串T的數目。如樣例中的第一個為刪掉第一個b,第二個為刪除第二個b,第三個為刪除第三個b,因此數量為3.
首先想到的方法是回溯法。可是遇到長串時超時。裡面包括太多反覆子問題。
程式碼例如以下:Time Limit Exceeded
class Solution { public: int numDistinct(string S, string T) { num = 0; if(S.length() < T.length()){ return num; } numDistinctCore(S,T,0,0); return num; } void numDistinctCore(string& S,string& T, int si, int tj){ int slen = S.length(); int tlen = T.length(); if(slen-si < tlen -tj){ return; } if(tj == tlen){ ++num; } for(int i = si; i<slen; ++i){ if(S[i] == T[tj]){ numDistinctCore(S,T,i+1, tj+1); } } } int num; };
考慮到回溯法子問題反覆求解。想到利用動態規劃的方法。此題有些像求最大公共字串,可是須要改動一下,尋找子問題。
設dp[i][j]為S字串截止到i時。能將S前面字串能轉換為T截止到j的子串的轉換次數。求dp[i][j]時。一種方法轉換時即刪除S[i],變回S[i-1][j]的問題。還有一種方法。假設S[i] == T[j]。則轉換為dp[i-1][j-1]的問題。
即為同樣時為 dp[i][j] = dp[i-1][j] + dp[i-1][j-1] 。不同一時候為 dp[i][j] = dp[i-1][j]
Accepted
class Solution {
public:
int numDistinct(string S, string T) {
int slen = S.length();
int tlen = T.length();
if(slen < tlen){
return 0;
}
int **dp = new int*[slen+1];
for(int i=0; i<slen+1; ++i){
dp[i] = new int[tlen+1];
dp[i][0] = 1;
}
for(int j=1; j<tlen+1; ++j){
dp[0][j] = 0;
}
for(int i=1; i<slen+1; ++i){
for(int j=1; j<tlen+1; ++j){
int temp = dp[i-1][j];
if(S[i-1] == T[j-1]){
temp += dp[i-1][j-1];
}
dp[i][j] = temp;
}
}
int result = dp[slen][tlen];
for(int i=0; i<slen+1; ++i){
delete[] dp[i];
}
delete[] dp;
return result;
}
};