题目链接:http://oj.leetcode.com/problems/word-break-ii/
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"]
.
code:
class Solution
{
public:
vector<string> ans;
vector<string> had;
vector<string> wordBreak(string s, unordered_set<string> &dict)
{
int LEN=s.size();
vector<vector<bool> > match(LEN+1,vector<bool>(LEN+1,false));
for(int i=0;i<=LEN;i++)
{
match[0][i]=true;//从i开始,长度为0的,当然为true了
}
for(int len=1;len<=LEN;len++)
{
for(int beg=0;beg+len<=LEN;beg++)
{
string tmp=s.substr(beg,len);
if(dict.count(tmp)>0)
{
match[len][beg]=true;
}
else//看能不能由以前的状态推出来
{
for(int plen=1;plen<len;plen++)
{
match[len][beg]=match[len-plen][beg+plen]&match[plen][beg];
if(match[len][beg])
break;
}
}
}
}
if(match[LEN][0]==false)
{
return vector<string> ();
}
ans.clear();
had.clear();
dfs(s,0,match,dict);
return ans;
}
void dfs(string &s,int k,vector<vector<bool> > &match,unordered_set<string> &dict)
{
int LEN=s.size();
if(k>=LEN)
{
if(!had.empty())
{
string res;
for(int i=0;i<had.size();i++)
{
res+=had[i];
if(i!=had.size()-1)
res+=" ";
}
ans.push_back(res);
return;
}
}
for(int len=1;k+len<=LEN;len++)
{
string tmp=s.substr(k,len);
if(dict.count(tmp)>0&&match[LEN-k-len][k+len])
{
had.push_back(tmp);
dfs(s,k+len,match,dict);
had.pop_back();
}
}
}
};