Given A string s and a Dictionary of words dict, add spaces in s to construct a sentence where Each of the word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
The problem is word break's follow up. Now is not the time to judge whether or not to break, but to give all the break situations. If you use pure search+backtrack to be tle, this is done as follows:
classsolution (object):defWordbreak (self, S, worddict):""": Type S:str:type worddict:set[str]: rtype:list[str]""" if notSor notworddict:return[] MaxLen=0 forWinchWorddict:maxlen=Max (MaxLen, Len (w)) hash=Set (worddict) Res=[] Self.search (S, hash, res, [], 0, maxlen) Res=Self.gen_result (res, s)returnResdefSearch (self, s, hash, res, cur, index, maxlen):ifindex = =Len (s): Res.append (cur+[index])returncur.append (Index) forIinchXrange (1,maxlen+1): ifS[index:index+i]inchHash:self.search (S, hash, res, cur, index+I, MaxLen) Cur.pop ()defGen_result (self, res, s): tmp= [] forIinchxrange (len (res)): Arr= [] forJinchXrange (0,len (res[i))-1): Arr.append (S[res[i][j]: res[i][j+1]]) tmp.append (' '. Join (arr))returnTmp
How to improve it ~ Why the search complexity is high, mainly in the repeated segmentation, if the sub-segments that need to be segmented before the split before, it is a waste of time to process again. A space-for-time approach is to save all possible strings of previously processed substrings, which is a memory search method. Space in exchange for time. The code is as follows:
classsolution (object):defWordbreak (self, S, worddict):""": Type S:str:type worddict:set[str]: rtype:list[str]""" #Pure Search and backtracking is TLE, using the memory search method, #ie, a Dict object to store the result of the current tackling substrCache ={} result=Self.helper (S, worddict, cache)returnresultdefHelper (self, S, worddict, cache):ifSinchCache:returnCache[s] Result= [] ifSinchWordDict:result.append (s) forIinchXrange (1, Len (s)): Word=S[i:]ifWordinchWorddict:rem=S[:i] Prev=self.combine (Word, Self.helper (REM, worddict, cache)) result+=prev Cache[s]= result + [] returnresultdefCombine (self, word, prev):#Word is a string, and Prev is a list of string, tmp = [] for i in Xrange (Len (prev)): Tmp.append (Prev[i] + "+ word) # Note that this paragraph must be written so as to prevent direct changes to the prev resulting in The cache is affected by the direct changes that exist. return TMP
Word Break II