Word Break II

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

DFS+剪枝

是前面那拆分词语的扩展,除了要判断能否由字典里的词语组成,还要求出所有的组合。

单纯的DFS会TLE,需要剪枝。

class Solution{
private:
    void helper(string& s,unordered_set<string>& wordDict,int start,vector<bool>& possible,string path,vector<string>& res){
        if(start == int(s.length())){
            res.push_back(path);
            return;
        }
        for(int i = start;i<int(s.length());i++){
            string word = s.substr(start,i-start+1);
            if(wordDict.find(word) != wordDict.end() && possible[i+1]){
                if(start == 0)
                    path.append(word);
                else{
                    path.append(" ");
                    path.append(word);
                }
                int oldsize = res.size();
                helper(s,wordDict,i+1,possible,path,res);
                if(int(res.size()) == oldsize) possible[i+1] = false;
                if(start == 0)
                    path.resize(path.size() - word.size());
                else
                    path.resize(path.size() - word.size()-1);
            }
        }
    }
public:
    vector<string> wordBreak(string s,unordered_set<string>& wordDict){
        vector<string> res;
        vector<bool> possible(s.size()+1,true);
        helper(s,wordDict,0,possible,"",res);
        return res;
    }
};

 

 

posted @ 2016-12-13 20:55  wxquare  阅读(207)  评论(0编辑  收藏  举报