题目地址:点击打开链接
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
n=s.size();
father=vector<vector<bool>>(n+1,vector<bool>(n+1,false));
vector<bool> f(n+1,false);
f[0]=true;
for(int i=1;i<=n;++i){
for(int j=i-1;j>=0;--j){
if(f[j]&&wordDict.count(s.substr(j,i-j))>0){
f[i]=true;
father[i][j]=true;
}
}
}
vs.clear();
if(f[n]==false)return vs;
dfs(n,s,"");
return vs;
}
private:
vector<vector<bool>> father;
vector<string> vs;
int n;
void dfs(int index,string s, string str) {
if(index==0){
vs.push_back(str);
return;
}
for(int i=0;i<=n;++i) {
if(father[index][i]){
dfs(i,s,s.substr(i,index-i)+(str==""?"":" "+str));
}
}
}
};