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;
        }
    };

     

  • 相关阅读:
    第4章 Java并发编程的基础
    第3章 Java内存模型
    Ajax请求重复发送问题
    React的Hook函数之React.useState()、React.useEffect()
    Ajax GET请求和POST请求的基本操作
    使用pubsub-js来做消息的订阅和发布
    React配置代理解决跨域问题
    React中的函数式组件和类式组件
    JSX语法规则
    Hello React!
  • 原文地址:https://www.cnblogs.com/wxquare/p/6171483.html
Copyright © 2011-2022 走看看