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"]
.
先对单词表建trie树,然后dfs就好
但直接dfs会导致超时。
优化方式是:建一个map,存下搜索过的string s的所有答案,虽然空间消耗大,但是减少了dfs次数
struct node
{
vector<node*> a;
bool word;
node()
{
word = false;
a.resize(26,NULL);
}
};
class Solution {
public:
node* root;
set<string> SET;
vector<string> ans;
map<string, vector<string>> mp;
void insert(string word)
{
node* now = root;
for(int i=0;i<word.size();i++)
if(now->a[ word[i]-'a' ]!=NULL)
now = now->a[ word[i]-'a' ];
else
{
now->a[ word[i]-'a' ] = new node();
now = now->a[ word[i]-'a' ];
}
now->word = true;
}
vector<string> getans(string s, node* r)
{
if(mp.find(s)!=mp.end())return mp[s];
vector<string> res;
if(!s.length())
{
res.push_back("");
mp[s] = res;
return mp[s];
}
node* now = r;
int l = s.length();
for(int i = 0 ; i < l ; ++i )
{
if(now->a[ s[i]-'a' ])
now = now->a[ s[i]-'a' ];
else
{
mp[s] = res;
return mp[s];
}
if(now->word)
{
vector<string> nxt = getans(s.substr(i+1),r);
for(auto iter: nxt)
{
string tmp = s.substr(0,i+1) + (iter.length()?" ":"") + iter;
res.push_back(tmp);
}
}
}
mp[s] = res;
return mp[s];
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict)
{
root = new node();
for(auto iter = wordDict.begin();iter!=wordDict.end();iter++)
insert(*iter);
vector<string> ans = getans(s,root);
return ans;
}
};