问题描述如下:
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"]
.
cpp代码如下:
class Solution {
private:
vector<string> ans;
vector<string> tmp;
vector<bool> flag;
bool wordbreak(const string& s,int pos,const unordered_set<string>& dict){
if(pos==s.length()){
string t="";
for(int i=0;i<tmp.size();++i){
t+=tmp[i]+" ";
}
t.resize(t.size()-1);
ans.push_back(t);
return true;
}
if(flag[pos]==false)return false;
string c="";
bool f=false;
for(int i=pos;i<s.length();++i){
c+=s[i];
if(dict.count(c)!=0){
tmp.push_back(c);
if(wordbreak(s,i+1,dict))f=true;
tmp.pop_back();
}
}
flag[pos]=f;
return f;
}
public:
vector<string> wordBreak(string s, unordered_set<string> &dict) {
ans.clear();
tmp.clear();
flag.resize(s.length());
for(int i=0;i<s.length();++i)
flag[i]=true;
wordbreak(s,0,dict);
return ans;
}
};