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"] .
Similar to Word break, use dynamic planning and solve using the Bottom-up method.
1vector<string> Wordbreak (stringS, unordered_set<string> &dict)2 {3vector<BOOL> Table (s.size () +1,false);4vector<vector<string> > Strtable (s.size () +1);5table[0] =true;6 7 for(inti =1; I <= s.size (); i++)8 {9 for(intj =0; J < I; J + +)Ten { One if(Table[j] = =false) A Continue; - if(Dict.find (S.substr (J, i-j))! =dict.end ()) - { theTable[i] =true; - if(strtable[j].size () = =0) - { -Strtable[i].push_back (S.substr (J, I-j)); + } - Else + { A for(intK =0; K < Strtable[j].size (); k++) at { - stringTMPSTR = Strtable[j][k] +" "+ S.SUBSTR (j, I-j); - Strtable[i].push_back (TMPSTR); - } - } - } in } - } to + returnstrtable[s.size ()]; -}
Memory Limit exceed will be sent after submission.
Leetcode 140. Word Break II