标签:
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"]
.
和Word Break 类似,使用动态规划,并使用bottom-up方法求解。
1 vector<string> wordBreak(string s, unordered_set<string> &dict) 2 { 3 vector<bool> table(s.size() + 1, false); 4 vector<vector<string> > strtable(s.size() + 1); 5 table[0] = true; 6 7 for (int i = 1; i <= s.size(); i++) 8 { 9 for (int j = 0; j < i; j++) 10 { 11 if (table[j] == false) 12 continue; 13 if (dict.find(s.substr(j, i - j)) != dict.end()) 14 { 15 table[i] = true; 16 if (strtable[j].size() == 0) 17 { 18 strtable[i].push_back(s.substr(j, i - j)); 19 } 20 else 21 { 22 for (int k = 0; k < strtable[j].size(); k++) 23 { 24 string tmpstr = strtable[j][k] + " " + s.substr(j, i - j); 25 strtable[i].push_back(tmpstr); 26 } 27 } 28 } 29 } 30 } 31 32 return strtable[s.size()]; 33 }
提交后会Memory Limit Exceed.
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4230469.html