class Solution {
public:
unordered_map<string,vector<string>> map;
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> all;
if(wordDict.empty()) return all;
unordered_set<string> set(wordDict.begin(),wordDict.end());
all = myword(s,set);
return all;
}
vector<string> myword(string s,unordered_set<string>& set){
if(map.count(s)) return map[s];
vector<string> res;
if(set.count(s)) res.push_back(s);
for(int i=0;i<s.length();i++){
string pre=s.substr(0,i+1);
string aft=s.substr(i+1,s.length()-(i+1));
if(set.count(pre))
{
vector<string> aft_string = myword(aft,set);
for(string j:aft_string)
{
res.push_back(pre+" "+j);
}
}
}
map[s]=res;
return res;
}
};
回溯算法,对于一个目标串s,遍历每一个可以分割的位置,判断,如果前缀在词表中,递归找到后缀所有可能的句子,如果返回结果不空,分别跟前缀组合,放入当前串s的结果集中。函数返回前,把找到的分割存到缓存map中,下次遇到相同的直接取就可以了。递归返回条件,如果串s已经在map中,直接返回结果,如果当前s在字典中,但是不在map,存入map。