zoukankan      html  css  js  c++  java
  • 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;
        }
    };

     

  • 相关阅读:
    python两个类之间变量和函数的调用
    ubuntu远程桌面设置
    ROS节点分布式运行方法
    pandaboard串口通信调试
    linux下查看cpu使用情况
    树莓派LED指示灯说明
    python多线程实践小结
    关系模型关系模型
    栈和队列的应用
    栈和队列
  • 原文地址:https://www.cnblogs.com/wxquare/p/6171483.html
Copyright © 2011-2022 走看看