Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Yu'sCodingGarden:leetcodeQuestion27:DistinctSubsequences
1
More NextBlog
CreateBlog SignIn
Yu'sCodingGarden
Everygeekhadadream...
Tuesday,January1,2013
leetcodeQuestion27:DistinctSubsequences
DistinctSubsequences
Rs.299
New Deals Every
Day
Amazon.in
GivenastringSandastringT,countthenumberofdistinctsubsequencesofTinS.
Asubsequenceofastringisanewstringwhichisformedfromtheoriginalstringbydeletingsome(canbenone)ofthe
characterswithoutdisturbingtherelativepositionsoftheremainingcharacters.(ie, "ACE" isasubsequence
of "ABCDE" while "AEC" isnot).
Hereisanexample:
S= "rabbbit" ,T= "rabbit"
Return 3 .
WhoamI?
CurrentlyIamaPh.D.candidatein
ComputerScience,myresearchfocuseson
machinelearningandcomputervision
Analysis:
Inotherword,thisquestionaskhowmanytimeThasoccurredinS,wheresomecharcanbeaddedinbetweenT,but
Myhomepage:(1)(2)
MyGoogleScholarPage:here
theorderofTcannotchange.
Aneasybuttimeconsumingideaisrecursion.Detailscanbefoundinthesourcecode.However,thisalgorithmcannot
passthelargetest.
New!!!
IamstartingtoaddPythonCodefor
theproblems!!!
Abetterwayis
(Updated201308)
Usefullink:C++reference
Theideaisusingdynamicprogramming(DP).
*******************************************
Firstweredefinetheproblemtoanotherform.
e.g.S="aabb"T="aab",weneedtofindtheoccurrenceofTinS,so,
leetcodeonlineJudgeProblemList
(1)WestorethepositionsofeachletterofTinS,inatable:
a[0,1]
*******************************************
a[0,1]
b[2,3]
(2)Theproblemthencanbeviewedas"findhowmanypathsfromtoptothebottomwithanascendingorder".
Basics:
Inotherwords,fromthetableabove,for"a"wehaveonlyonechoice0,theother"a"wehaveonlyonechoice
CommonSortingAlgorithms
1,andforbwecanchoose2or3,thustheresultis2.
HashTableBasics
Howtogetthepathnumber?youcanusedfs,butitmightbetimeconsuming.
TreeTraversal(Recursive&Non
Recursive)
Here,weuseDP,defineres[i][j]thenumberofpathcanhavefortable[i][j]
res[i][j]=sum(res[i1][k]),wheretable[i1][k]<table[i][j].
Thefinalresultisthesum(res[lastrow]).
Searchtheleetcodesolutionshere:
Thecode(Alltestcasespassed):
Search
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution{
public:
voidcond(vector<vector<int>>&table,int&res){
introw=table.size();
vector<vector<int>>r(row);
for(inti=0;i<table[0].size();i++){
r[0].push_back(1);
}
for(inti=1;i<table.size();i++){
inttmp=0;
intbf=0;
for(intj=0;j<table[i].size();j++){
for(intk=bf;k<table[i1].size();k++){
if(table[i][j]>table[i1][k]){
http://yucoding.blogspot.in/2013/01/leetcodequestion27distinct.html
IstartedtopostC++Solutionsforthe
famousbook:
CrackingTheCodingInterview(5th
Edition)
PleaseLookatmygitHub:here
(Regularlyupdate)
Note:
Allthecodeprovidedfortheleetcode
1/4
8/17/2015
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Yu'sCodingGarden:leetcodeQuestion27:DistinctSubsequences
tmp=tmp+r[i1][k];
bf=k+1;
}else{break;}
}
r[i].push_back(tmp);
}
}
for(inti=0;i<table[row1].size();i++){
res=res+r[row1][i];
}
}
intnumDistinct(stringS,stringT){
//StarttypingyourC/C++solutionbelow
//DONOTwriteintmain()function
if(S.empty()||T.empty()){return0;}
intres=0;
vector<vector<int>>table(T.size());
map<char,vector<int>>mp;
vector<int>r;
for(inti=0;i<T.size();i++){mp[T[i]]=r;}
for(inti=0;i<S.size();i++){mp[S[i]].push_back(i);}
for(inti=0;i<T.size();i++){table[i]=mp[T[i]];}
cond(table,res);
returnres;
}
};
questionshavebeentested
andhavepassedbothsmallandlarge
testsoftheonlinejudge
systemfromleetcode.
Pages
Home
ThisworkislicensedunderaCreative
CommonsAttributionNonCommercial
ShareAlike3.0UnportedLicense.
Labels
answer(1)array(11)backtracking(1) BFS(12)
binary search (6) bit manipulations (5) BST (1)
bubble sort (1) bucket sort (1) c++ (1) collision (1)
commonprefix(1)compare(1)design(1)DFS(14)
dict (2) divide and conquer (1) DP (7) graph (2)
Theoldsourcecode(onlycanpasssmalltest):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
iterator(1)
classSolution{
public:
intcond(stringS,stringT){
if(S.size()==0){return0;}
if(T.size()==0){return1;}
if((S.size()==1)&&(T.size()==1)){
if(S[0]==T[0]){return1;}
else{return0;}
}
if(S[0]==T[0]){
returncond(S.substr(1),T.substr(1))+cond(S.substr(1),T);
}else{
returncond(S.substr(1),T);
}
}
intnumDistinct(stringS,stringT){
//StarttypingyourC/C++solutionbelow
//DONOTwriteintmain()function
if(S.empty()||T.empty()){return0;}
returncond(S,T);
}
};
(7) list (1) loop (5) map (3) mask (1) math (2)
mergesort(2) minimumsubstring(1)nonrecursive
(1)O(n)(1)onlinejudge(1)oop(1) permutations (1)
pointers (7) postorder(1) preorder (2) python (1)
questions(1)quicksort(1)radixsort(1)Review (3)
BlogArchive
2017(1)
2015(26)
2014(15)
2013(126)
Dec2013(14)
PostedbyYuZhuat6:10PM
Labels:DFS,DP,leetcode
Oct2013(3)
Sep2013(2)
Aug2013(6)
8comments:
Jul2013(1)
May2013(18)
JiantaoWu March30,2013at10:13AM
Nicesolution.
Mar2013(6)
Onesmallbug:line20,ifTisemptythenitshouldreturn1insteadof0.
Also,line5seemstobeunnecessary.
IthinkprobablyanotherspecialcasetocheckisthatSandTarebothempty.
Don'tknowifthisisnecessarybutIthinkemptystringshouldbeasubstringofanystring,includingemptystring
itself.
Reply
Replies
YuZhu
Apr2013(32)
March30,2013at10:31AM
Thanksforyourkindreply!
Yes.Doesthatmakesenseifline5changethe"or"to"and"?
Andthisisjustananswerthatcannotpassthelargetest,I'llpostthebetteranswerASAP.
Thanks.
http://yucoding.blogspot.in/2013/01/leetcodequestion27distinct.html
Feb2013(9)
Jan2013(35)
leetcodeQuestion60:N
QueensII
leetcodeQuestion59:N
Queens
leetcodeQuestion58:
MultiplyStrings
leetcodeQuestion57:
MinimumWindow
Substring
leetcodeQuestion56:
MinimumPathSum
leetcodeQuestion55:
MinimumDepthofBinary
Tree...
leetcodeQuestion54:Merge
TwoSortedLists
2/4
8/17/2015
Yu'sCodingGarden:leetcodeQuestion27:DistinctSubsequences
JiantaoWu March31,2013at8:23PM
leetcodeQuestion53:Merge
SortedArray
Ithinkitshouldbe:
leetcodeQuestion52:Merge
kSortedLists
if(T.empty())
returntrue
leetcodeQuestion51:Merge
Intervals
if(S.empty())
returnfalse
leetcodeQuestion50:
MedianofTwoSorted
Arrays
IfTisempty,thenitshouldbealwaystrue.
IfTisnotemptyandSisempty,thenitshouldbefalse.
leetcodeQuestion49:
Maximumsubarray
Reply
leetcodeQuestion48:
MaximumDepthofBinary
Tree...
leetcodeQuestion47:
MaximalRectangle
NisonLi January8,2014at10:27AM
classSolution{
public:
intnumDistinct(stringS,stringT){
intm=S.size()
intn=T.size()
vector>memo(m+1,vector(n+1,0))
for(inti=0i<=mi++)
memo[i][0]=1
for(inti=1i<=mi++)
{
for(intj=1j<=nj++)
{
if(S[i1]==T[j1])
memo[i][j]+=memo[i1][j1]
memo[i][j]+=memo[i1][j]
}
}
returnmemo[m][n]
}
}
Reply
XingHuang July2,2014at6:50AM
intnumDistinct(stringS,stringT)
{
vectorf(T.size()+1)
f[0]=1
for(inti=0i<S.size()++i)
{
for(intj=T.size()1j>=0j)
{
f[j+1]+=S[i]==T[j]?f[j]:0
}
}
returnf[T.size()]
}
Reply
RahulKumar June19,2015at3:12AM
canyouhelpmetounderstandproblem.
S="rabbbit",T="rabbit"
ThasmanydistinctsubsequenceEg.rabbit,rab,rait,rabit,ait,bit,ansmanymore
ansallofthempresentinS.
Thenhowtheansweris3.
Thanksinadvance
Reply
traceformula August16,2015at4:37AM
leetcodeQuestion46:
LongestValidParentheses
leetcodeQuestion45:
LongestSubstringWithout
Re...
leetcodeQuestion44:
LongestPalindromic
Substrin...
leetcodeQuestion43:
LongestCommonPrefix
leetcodeQuestion42:Letter
CombinationsofaPho...
leetcodeQuestion41:
LengthofLastWord
leetcodeQuestion40:
LargestRectanglein
Histogr...
leetcodeQuestion39:Jump
GameII
leetcodeQuestion38:Jump
Game
leetcodeQuestion37:
InterleavingString
leetcodeQuestion36:
IntegertoRoman
leetcodeQuestion35:Insert
Interval
leetcodeQuestion34:
ImplementstrStr()
leetcodeQuestion32:Gary
code
leetcodeQuestion31:
GenerateParentheses
leetcodeQuestion30:
FlattenBinaryTreeto
Linke...
leetcodeQuestion29:First
MissingPositive
leetcodeQuestion28:Divide
twointegers
leetcodeQuestion27:
DistinctSubsequences
leetcodeQuestion26:
DecodeWays
leetcodeQuestion25:Count
andSay
2012(29)
Ihaveasolutionusinglessspace:
publicclassSolution{
publicintnumDistinct(Strings,Stringt){
if(s==null||t==null||t.length()==0)return0
int[]dp=newint[t.length()]
http://yucoding.blogspot.in/2013/01/leetcodequestion27distinct.html
3/4
8/17/2015
Yu'sCodingGarden:leetcodeQuestion27:DistinctSubsequences
for(inti=0i=0j){
if(c==t.charAt(j)){
dp[j]=dp[j]+(j!=0?dp[j1]:1)
}
}
}
returndp[t.length()1]
}
}
URL:http://traceformula.blogspot.com/2015/08/distinctsubsequences.html
Reply
traceformula August16,2015at4:37AM
Ihaveasolutionusinglessspace:
publicclassSolution{
publicintnumDistinct(Strings,Stringt){
if(s==null||t==null||t.length()==0)return0
int[]dp=newint[t.length()]
for(inti=0i=0j){
if(c==t.charAt(j)){
dp[j]=dp[j]+(j!=0?dp[j1]:1)
}
}
}
returndp[t.length()1]
}
}
URL:http://traceformula.blogspot.com/2015/08/distinctsubsequences.html
Reply
Enteryourcomment...
Commentas:
Publish
GoogleAccount
Preview
NewerPost
Home
OlderPost
Subscribeto:PostComments(Atom)
FROM
10/08/2015
FlytoNewDelhi
Rs.3,848
Booknow
Copyright20122014Yu'sCodingGardenAllRightsReserved..AwesomeInc.template.TemplateimagesbyJasonMorrow.PoweredbyBlogger.
http://yucoding.blogspot.in/2013/01/leetcodequestion27distinct.html
4/4