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;
    }
    };
  • 相关阅读:
    POJ 2251 Dungeon Master
    POJ1321棋盘问题
    CODE[VS] 1003 电话连线
    CCF-201412-1-门禁系统
    CCF-201412-2-Z字形扫描
    为什么要用补码
    CCF-201409-1-相邻数对
    CCF-201409-2-画图
    CCF-201403-1-相反数
    CCF-201403-2-窗口
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281233.html
Copyright © 2011-2022 走看看