Leetcode之递归之苦

自从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()]即可。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值