题目描述
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"].
1
class Solution {
2
public:
3
//动态规划思想,记录子问题结果。。。。
4
unordered_map<string,vector<string>> hash;//加快执行速度。。。递归有使用,需外部声明
5
vector<string> wordBreak(string s, unordered_set<string> &dict) {
6
if(hash.find(s)!=hash.end())
7
return hash[s];
8
9
vector<string> res;
10
11
if(s.size()==0)
12
return res;
13
if(dict.find(s)!=dict.end())
14
res.push_back(s);//
15
16
for(int i=0;i<s.size();i++){
17
string pre=s.substr(0,i+1);
18
if(dict.find(pre)==dict.end())
19
continue;
20
string post=s.substr(i+1);
21
vector<string> tmp=wordBreak(post,dict);
22
for(int j=0;j<tmp.size();j++){
23
res.push_back(pre+" "+tmp[j]);
24
}
25
}
26
hash[s] = res;
27
return res;
28
}
29
};