[Question]
Given a string s and a dictionary of words dict, add spaces in S to construct a sentence where each 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"]
.
Question]
Given a word s and a dictionary dict, all split conditions are returned so that each word is a word in dict.
[Idea]
Determine the set of precursor words ending with each position I in turn (as long as you remember the end position of the precursor word)
Then restore the splitting path from the back to the back.
DP Problems
[Code]
Class solution {public: void recoverpath (vector <string> & result, vector <string> & words, string & S, Map <int, vector <int> preorders, int end) {vector <int> preorder = preorders [end]; for (INT I = 0; I <preorder. size (); I ++) {string word = S. substr (preorder [I] + 1, end-preorder [I]); If (preorder [I] =-1) {string cutstr = word; int size = words. size (); For (Int J = size-1; j> = 0; j --) {cutstr + = "" + words [J];} result. push_back (Cutstr);} else {words. push_back (Word); recoverpath (result, words, S, preorders, preorder [I]); words. pop_back () ;}}vector <string> wordbreak (string S, unordered_set <string> & dict) {vector <string> result; If (S. length () = 0) return result; Map <int, vector <int> preorders; // records the precursor set vector <int> pos (1, -1); // to determine the sharded position for (INT I = 0; I <S. length (); I ++) {vector <int> preorder; For (int K = 0; k <POS. siz E (); k ++) {If (dict. Find (S. substr (Pos [k] + 1, I-pos [k])! = Dict. end () {preorder. push_back (Pos [k]) ;}} if (preorder. size ()> 0) {preorders [I] = preorder; POS. push_back (I) ;}/// restore all possible split paths if (preorders. find (S. length ()-1) = preorders. end () return result; vector <string> words; recoverpath (result, words, S, preorders, S. length ()-1); return result ;}};