140. Word Break II

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.

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"].

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.


上题,我用递归没解出来,这题上头了必须用递归写出来。

然而time limit exceeded,百思不得其解

在discuss中看见这样一段话

if you are getting TLE despite the correct DP or DFS solution, it might be because the largest test input is like this

["aa..(lots of 'a').b", "a","aaaaa"...so on]

As you can see this test case should return empty as last character in input string is b, which is not in the dictionary. So all the work in DP/DFS is a waste

To escape from TLE, just put a check first whether the input string s is breakable or not..if breakable then try to break it using your algo


一堆a中出了一个b!原来只要加一个判断是否可分割即可

附上自己的代码:

class Solution {
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        vector<string> res;
        unordered_set<int> visited;
        if(breakable(s,wordDict))
            help(s,wordDict,res,"",0);
        return res;
    }
    void help(string &s,vector<string> &wordDict,vector<string> &res,string temp,int index){
        if(index==s.size()){
            res.push_back(temp);
            return;
        }
        for(int i=index;i<s.size();i++){
            string t=s.substr(index,i-index+1);
            if(find(wordDict.begin(),wordDict.end(),t)!=wordDict.end()){
                t+=i==s.size()-1?"":" ";
                help(s,wordDict,res,temp+t,i+1);
               }
           }
     }
    
    bool breakable(string &s,vector<string> &wordDict){
        if(wordDict.size()==0) return false;  
        vector<bool> dp(s.size()+1);  
        dp[0]=true;  
        for(int i=1;i<=s.size();i++){  
            for(int j=i-1;j>=0;j--){  
                if(dp[j]){  
                    string temp=s.substr(j,i-j);  
                    if(find(wordDict.begin(),wordDict.end(),temp)!=wordDict.end()){  
                        dp[i]=true;  
                        break;  
                    }  
                }  
            }  
        }  
        return dp[s.size()];
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值