class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> set(wordDict.begin(), wordDict.end());
unordered_map<int,vector<string>> map;
return _wordBreak(s,set,map,0);
}
vector<string> _wordBreak(string s, unordered_set<string>& set,
unordered_map<int,vector<string>>& map,int index) {
if(map.count(index))
return map[index];
vector<string> res;
if(index == s.size())
res.emplace_back("");
else{
for(int i=index+1;i<=s.size();++i){
string sub = s.substr(index,i-index);
if(set.count(sub)){
vector<string> tmp = _wordBreak(s,set,map,i);
for(auto& j:tmp)
res.push_back(sub+(j.empty()?"":" ")+j);
}
}
}
map[index]=res;
return res;
}
};