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"].
That is, it is necessary to determine whether the string can be dictionary-separated, and to find all possible combinations. Refer to the DP idea of the word break question. First, look at the string s from the end, capture an existing word (Milestone 1) cyclically, and then recursion at the position of the truncation to continue looking forward, continue to intercept... Knowing the arrival of the header, then combine an answer; then enter the next loop at milestone 1, such as Milestone 1
', Intercept another word and find another answer...
The Code is as follows:
Class solution {vector <string> midres; vector <string> res; vector <bool> * DP; public: vector <string> wordbreak (string S, unordered_set <string> & dict) {int Len = S. length (); dp = new vector <bool> [Len]; for (INT I = 0; I <Len; ++ I) {for (Int J = I; j <Len; ++ J) {If (dict. find (S. substr (I, j-I + 1 ))! = Dict. end () {DP [I]. push_back (true); // The subscript of the second dimension is actually: Word Length-1} else {DP [I]. push_back (false); // The second dimension of the array uses vector, the size is not necessarily N, which saves space than N * n} func (S, len-1); Return res ;} void func (const string & S, int I) {if (I> = 0) {for (Int J = 0; j <= I; ++ J) {If (DP [J] [I-j]) {// note that the second subscript here is I-j, not I, because the length of the second-dimensional array is not fixed, the subscript of the Second-dimensional array is actually the word length-1 midres. push_back (S. substr (J, I-j + 1); func (S, J-1); midres. pop_back (); // continue to consider the next segment of the For Loop} return;} else {string STR; For (int K = midres. size ()-1; k> = 0; -- k) {// note that the traversal order is reverse STR + = midres [k]; // note that K is here, not I if (k> 0) STR + = "";} res. push_back (STR); Return ;}}};
Note the recursive function technique. Use the global variable res to save the answer. The intermediate result is saved to RES each time the recursion reaches the header.