class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict)
{
const int n=s.length();
vector<bool> result(n,false);
for(int i=0;i<n;++i)
{
if(wordDict.count(s.substr(0,i+1)))
{
result[i]=true;
continue;
}
for(int j=0;j<i;++j)
{
if(result[j]&&wordDict.count(s.substr(j+1,i-j)))
{
result[i]=true;
break;
}
}
}
vector<string> str;
string temp;
if(result[n-1])
dfs(str,temp,wordDict,result,0,s);
return str;
}
void dfs(vector<string>& str, string& temp,unordered_set<string>& wordDict,vector<bool> &result,int start,string & s)
{
if(start==s.length())
{
str.push_back(temp);
return;
}
for(int i=start;i<s.length()-1;++i)
{
if(result[i])
{
if(i==s.length()-1)
temp=temp+s.substr(start,i-start+1);
else
temp=temp+s.substr(start,i-start+1)+" ";
dfs(str,temp,wordDict,result,i+1,s);
temp.clear();
}
}
}
};