zoukankan      html  css  js  c++  java
  • leetcode[140]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"].

    class Solution {
    public:
    void dfs(string s, map<int,vector<int>> &fmap,int end, string str, vector<string> &res)
    {
        if(end<0)
        {
            res.push_back(str.substr(0,str.size()-1));
            return;
        }
        for (int j=0;j<fmap[end].size();j++)
        {
            string str1=s.substr(fmap[end][j]+1,end-fmap[end][j])+" ";
            str=str1+str;
            dfs(s,fmap,fmap[end][j],str,res);
            str=str.substr(str1.size(),str.size()-str1.size());
        }
        return;
    }
    vector<string> wordBreak(string s, unordered_set<string> &dict) 
    {
        vector<string> res;
        if(s.empty()||dict.empty())return res;
        vector<bool> dp(s.length()+1,false);
        dp[0]=true;
        map<int,vector<int>> fmap;
        for(int i=1;i<=s.length();i++)
        {
            for (int j=0;j<i;j++)
            {
                if(dp[j]&&dict.count(s.substr(j,i-j)))
                {
                    dp[i]=true;
                    if(j>=0)fmap[i-1].push_back(j-1);
                }
            }
        }
        string str="";
        int end=s.length()-1;
        dfs(s, fmap, end, str,res);
        return res;
    }
    };
  • 相关阅读:
    mongodb将mysql数据导入
    mongodb增删改查操作
    mongdb安装
    Python获取两个文件的交集、并集、差集
    java回调函数详解
    java线程锁之synchronized
    mysql知识点汇集
    Springboot2.0实现URL拦截
    idea将springboot打包成jar或者war
    leetcode1128
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281233.html
Copyright © 2011-2022 走看看