Word Break II
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"].
Solution: check before constructing the sentences.
1 class Solution { 2 public: 3 vector<string> wordBreak(string s, unordered_set<string> &dict) { 4 vector<string> res; 5 if (!wordBreakPossible(s, dict)) return res; //! not pass if ignoring here 6 wordBreakRe(s, dict, 0, "", res); 7 return res; 8 } 9 10 void wordBreakRe(const string &s, const unordered_set<string> &dict, 11 int start, string sentence, vector<string> &res) { 12 if (start == s.size()) { 13 res.push_back(sentence); 14 return; 15 } 16 if (start != 0) sentence.push_back(' '); 17 for (int i = start; i < s.size(); ++i) { 18 string word = s.substr(start, i-start+1); 19 if (dict.find(word) == dict.end()) 20 continue; 21 wordBreakRe(s, dict, i+1, sentence + word, res); 22 } 23 } 24 25 bool wordBreakPossible(const string &s, const unordered_set<string> &dict) { 26 int N = s.size(); 27 bool canBreak[N+1]; 28 memset(canBreak, false, sizeof(canBreak)); 29 canBreak[0] = true; 30 for (int i = 1; i <= N; ++i) { 31 for (int j = i-1; j >= 0; --j) { 32 if (canBreak[j] && dict.find(s.substr(j, i-j)) != dict.end()) { 33 canBreak[i] = true; 34 break; 35 } 36 } 37 } 38 return canBreak[N]; 39 } 40 };