Leetcode: Word break II [2, 140]

Source: Internet
Author: User
[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 ;}};


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.