Well, it seems that many people meet the TLE problem. Well, I use a simple trick in my code to AOIVD TLE. That's, each time before I try-to-break the string, and I call the function from Word break first to see wordBreak()
wheth Er it is breakable. If It isn't breakable, then we simply return an empty vector of string. Otherwise, we break it using backtracking.
The idea of backtracking is also typical. Start from 0
Index of the string, each time we see a new word, add it to a temporary solution string sol
. When we pass the end of the string, push to sol
a result vector res
. Then we need to recover back to their sol
original status before the word was added. So I simply the record another temporary variable each time temp
before I add a word to sol
.
The code is as follows. I hope it to be self-explanatory enough.
1 BOOLIswordbreak (string& S, unordered_set<string>&worddict) {2vector<BOOL> dp (s.length () +1,false);3dp[0] =true;4 intMinlen =Int_max;5 intMaxLen =int_min;6 for(stringword:worddict) {7Minlen = Min (Minlen, (int) word.length ());8MaxLen = Max (MaxLen, (int) word.length ());9 }Ten for(inti =1; I <= s.length (); i++) { One for(intj = I-minlen; J >= Max (0, I-maxlen); j--) { A if(Dp[j] && Worddict.find (S.substr (J, i-j))! =Worddict.end ()) { -Dp[i] =true; - Break; the } - } - } - returndp[s.length ()]; + } - voidBreakwords (stringSintIDX, unordered_set<string>& Worddict,string& Sol, vector<string>&Res) { + if(idx = =s.length ()) { ASol.resize (Sol.length ()-1); at Res.push_back (sol); - return; - } - for(inti = idx; I < s.length (); i++) { - stringWord = s.substr (idx, I-idx +1); - if(Worddict.find (word)! =Worddict.end ()) { in stringTMP =Sol; -Sol + + word +" "; toBreakwords (s, i +1, Worddict, Sol, res); +Sol =tmp; - } the } * } $vector<string> Wordbreak (stringS, unordered_set<string>&worddict) {Panax Notoginseng stringSol; -vector<string>Res; the if(!iswordbreak (S, worddict))returnRes; +Breakwords (s),0, Worddict, Sol, res); A returnRes; the}
[Leetcode] Word Break II