使用回溯法,第一次尝试超时了,因为穷举递归重复了很多次
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict)
{
vector<string>ret;
dfs(s,wordDict,"",ret);
return ret;
}
void dfs(string s,unordered_set<string> &wordDict,string str,vector<string>&ret)
{
if(s.size()==0)
{
ret.push_back(str);
return;
}
for(int i=1;i<=s.size();i++)
{
if(wordDict.find(s.substr(0,i))!=wordDict.end())
{
string temp=str.empty()?s.substr(0,i):str+" "+s.substr(0,i);
dfs(s.substr(i),wordDict,temp,ret);
}
}
}
};
改进方法:将求得的中间结果保存
class Solution {
unordered_map<string, vector<string>> m;//m中保存s.substr(0,i)的wordBreak的结果
vector<string> combine(string word, vector<string> prev){//将s后面的在dict中的word和前面的映射相加
for(int i=0;i<prev.size();++i){
prev[i]+=" "+word;
}
return prev;
}
public:
vector<string> wordBreak(string s, unordered_set<string>& dict) {
if(m.count(s))
return m[s]; //take from memory
vector<string> result;
if(dict.count(s)){ //a whole string is a word
result.push_back(s);
}
for(int i=1;i<s.size();++i){
string word=s.substr(i);
if(dict.count(word)){
string rem=s.substr(0,i);
vector<string> prev=combine(word,wordBreak(rem,dict));
result.insert(result.end(),prev.begin(), prev.end());
}
}
m[s]=result; //memorize
return result;
}
};
简化代码
lass Solution
{
private:
unordered_map<string, vector<string>> m;
public:
vector<string> wordBreak(string s, unordered_set<string>& dict)
{
if(m.find(s)!=m.end())
return m[s];
vector<string>ret;
if(dict.find(s)!=dict.end())
ret.push_back(s);
for(int i=1;i<s.size();i++)
{
string word=s.substr(i);
if(dict.find(word)!=dict.end())
{
vector<string> pre=wordBreak(s.substr(0,i),dict);
for(auto it=pre.begin();it!=pre.end();it++)
ret.push_back(*it+" "+word);
}
}
m[s]=ret;
return ret;
}
};