class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
//若i-j之间的字符串为字典某一单词 则令矩阵a[i][j]=1,获得可达图 进行深度优先搜索即可。
vector<string> vs;
bool a[1000][1000]={{0}};
bool dp[1000] = {false};
dp[0]=true;
int i;
int l = s.length();
for(i=0;i<l;i++){
if(dp[i]){
for(int len=1;i+len-1<l;len++){
if(wordDict.count(s.substr(i,len))>0){
dp[i+len]=true;
a[i][i+len-1]=true;
}
}
}
}
if(!dp[l]) return vs;//若dp[l]无法被分割 返回空向量
else { //否则进行深度遍历
string tmp="";
DFS(tmp,a,0,l,vs,s);
/*for(int i=0;i<vs.size();i++){
cout<<vs[i]<<endl;
}*/
}
return vs;
}
void DFS(string s,bool a[][1000],int n,int l ,vector<string> &vs1,string s1){//传参时 应注意传入向量的引用 否则只是对副本进行修改
for(int i=n;i<l;i++){
if(a[n][i]==true){
string copy;
if(n!=0){
copy = s+" "+s1.substr(n,i-n+1);}
else{
copy = s1.substr(n,i-n+1);
}
DFS(copy,a,i+1,l,vs1,s1);
if(i==l-1){vs1.push_back(copy);break;}
}
}
}
};
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.