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