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"]
.
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
if(m.find(s)!=m.end()) return m[s];
vector<string> sentences;
for(size_t i=0;i<s.size();++i){
string ts = s.substr(0,i+1);
unordered_set<string>::iterator iter = dict.find(ts);
if(iter!=dict.end()){//找到了此子串,那么递归
if(s.size() == i+1){
sentences.push_back(ts);
}else{
vector<string> postResult=wordBreak(s.substr(i+1,s.size()-i-1),dict);
if(postResult.size()){//后半部分可以分词
combineStr(ts,postResult,sentences);
}
}
}
}
m[s]=sentences;
return sentences;
}
private:
void combineStr(string ts,vector<string> &postResult,vector<string> &dest){
for(size_t i=0;i<postResult.size();++i){
dest.push_back(ts+" "+postResult[i]);
}
}
private:
map<string,vector<string>> m;
};