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"]
.
// I currently only do it using backtracking. But this has high complexity..... need to think about how to do it using DP.
void wordBreak(string s, int pos, vector< vector<string > >& res, vector<string>& path, unordered_set<string>& wordDict) { if(pos == s.size()) { res.push_back(path); return; } for(int i = pos; i < s.size(); ++i) { string tmp = s.substr(pos, i - pos + 1); if(wordDict.find(tmp) != wordDict.end()) { path.push_back(tmp); wordBreak(s, i + 1, res, path, wordDict); path.pop_back(); } } } vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector< vector<string> > res; vector<string> path; wordBreak(s, 0, res, path, wordDict); vector<string> result; for(int i = 0; i < res.size(); ++i) { string tmp = ""; for(int j = 0; j < res[i].size(); ++j) { tmp = tmp + " " + res[i][j]; } result.push_back(tmp); } return result; } // test int main(void) { string test = "aaaaa"; unordered_set<string> wordDict{"a", "aaa", "aa", "aaaaa", "aaaa"}; vector<string> res = wordBreak(test, wordDict); for(auto iter : res) { cout << iter << endl; } }