您的位置:首页 > 其它

leetcode:word break II

2015-12-15 21:22 477 查看
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"]
.

class Solution {
public:
bool dfs(string s,int start,  vector<string>& result, vector<string>& path,  unordered_set<string>& wordDict ,unordered_set <int> & unmatch)
{
if(start==s.size())
{
string tmp;
for(auto word : path )
{
tmp+=word;
tmp+=" ";
}
result.push_back(tmp.substr(0,tmp.size()-1));
return true;
}
bool ret=false;
for(int i=start; i<s.size(); i++)
{
string tmp = s.substr(start,i-start+1);
//如果在i的位置分割过,不匹配,那就不要处理,直接跳过在后面的位置判断
if(wordDict.count(tmp)>0 && unmatch.count(i)==0 )
{
path.push_back(tmp);
bool subRet=dfs(s,i+1, result, path, wordDict, unmatch);
path.pop_back();
if(subRet==false)
unmatch.insert(i);//记录下i的位置,在这里分割过了,没有匹配的,以后就不要再在这里分割了
else
ret=true;//为了告诉上一层,start 与start-1之间分开时可以匹配的
}
}
return ret;
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
unordered_set<int> unmatch;
vector<string> path;
vector<string> ret;
dfs(s, 0, ret, path, wordDict, unmatch);
return ret;
}
};
相关:word break I
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: