您的位置:首页 > 其它

leetcode:Word Break

2015-12-13 21:47 337 查看
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given

s =
"leetcode"
,

dict =
["leet", "code"]
.

Return true because
"leetcode"
can be segmented as
"leet
code"
.

思路:遍历每个可以分割的位置,在可以分割的位置递归进去看满足要求不,不满足要求就遍历下一个可以分割的位置


Submission Result: Time Limit Exceeded

Last executed input:"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
class Solution {
public:
bool dfs(string s,int start, unordered_set<string>& wordDict)
{
if(start==s.size())
return true;
bool ret=false;
for(int i=start; i<s.size(); i++)
{
string tmp = s.substr(start,i-start+1);
if(wordDict.count(tmp)>0)
{
ret=dfs(s,i+1,wordDict);
if(ret==true)
return  true;
}
}
return false;
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
return dfs(s, 0, wordDict);
}
};


递归 进去的时候,又从start位置往后遍历 ……递归----遍历…递归---遍历……

最后得出false 不符合条件,那就遍历下一个可以分割的位置,但是 这个位置可能前面的递归中已经遍历过来,不符合条件了,就不要再对这个位置分割处理了

总结:注意剪枝,剪枝,剪枝,去掉不需要的重复计算,用变量记录状态,去除掉不需要的重复状态

class Solution {
public:
bool dfs(string s,int start, unordered_set<string>& wordDict ,unordered_set <int> & unmatch)
{
if(start==s.size())
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 )
{
ret=dfs(s,i+1,wordDict, unmatch);
if(ret==true)
return  true;
else
unmatch.insert(i);//记录下i的位置,在这里分割过了,以后就不要再在这里分割了
}
}
return false;
}
bool wordBreak(string s, unordered_set<string>& wordDict) {
unordered_set<int> unmatch;
return dfs(s, 0, wordDict, unmatch);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: