自从2014年某月某日学会了利用递归进行枚举后,从此爱上该方法不可收拾,为啥?因为只要找到子结构就很好说啦,特别是在树中,等等。。。“子结构”,貌似DP中也有这一说法。今天就来谈谈我在Leetcode中利用递归的碰壁经历。
题目: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". (http://oj.leetcode.com/problems/word-break/)
洋洋洒洒我立马就写出了下面的代码:
class Solution {
public:
bool wordBreak(string s, set<string> &dict) {
if(s.length()==0) return true;
for(int index=s.length()-1;index>=0;index--){
if(dict.count(s.substr(0,index+1))){
if(wordBreak(s.substr(index+1), dict)) //当找到解时,返回true;否则进行下一次循环
return true;
}
}
return false;
}
};
提交后的结果是:
Submission Result: Time Limit Exceeded
好不容易这么快写出了代码,居然还超时!!看了discuss中人家说递归非常耗时,看来只能借用“记事本”方法了。
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
int sz=s.length();
if(sz==0) return false;
bool c[sz+1];
for(int i=1;i<sz+1;i++) c[i]=false;
c[0]=true;
for(int i=0;i<sz;i++){
if(c[i]){
unordered_set<string>::iterator it=dict.begin();
for(;it!=dict.end();it++){
string newstr=s.substr(0,i)+*it;
if(s.find(newstr)<s.length())
c[newstr.length()]=true;
}
}
}
return c[sz];
}
};
依然轻轻松松的解决了。这里用一维记事本c[i]表示字符串前i位是否可用dict表达,一次更新c,最终返回c[s.length()]即可。