zoukankan      html  css  js  c++  java
  • LeetCode "Word Break II"

    Since it is a "return all" problem, we can use DFS. But brutal DFS got a TLE. So pruning is required.

    I referred to http://fisherlei.blogspot.com/2013/11/leetcode-wordbreak-ii-solution.html

    So it's got AC:

    class Solution {
    public:
        vector<string> ret;
        vector<bool> ok;
        void go(string s, int from, vector<string> rec, unordered_set<string> &dict)
        {
            int len = s.length();
            if(len == 0)
            {
                string ss;
                
                for(int i = 0; i <rec.size(); i ++)
                {
                    ss += rec[i]; 
                    if((i+1)<rec.size()) ss += " ";
                }
                
                ret.push_back(ss);
                return;
            }
            for(int i = 1; i <= len; i ++)
            {
                string sub = s.substr(0, i);
                if (dict.find(sub) != dict.end() && ok[from])
                {
                    string rest = s.substr(i, len - i);
                    vector<string> newrec = rec; newrec.push_back(sub);
                    int preSize = ret.size();
                    go(rest, from + i, newrec, dict);
                    int postSize = ret.size();
                    if(preSize == postSize)
                        ok[from + i] = false;                
                }
            }
        }
        vector<string> wordBreak(string s, unordered_set<string> &dict) {
            int len = s.length();
            int lend= dict.size();
            if(len == 0 || lend == 0) return ret;
            
            ok.resize(len + 1);
            std::fill(ok.begin(), ok.end(), true);
    
            for(int i = 1; i <= len; i ++)
            {
                string sub = s.substr(0, i);
                if (dict.find(sub) != dict.end())
                {
                    string rest = s.substr(i, len - i);
                    vector<string> rec; rec.push_back(sub);
                    go(rest, i, rec, dict);
                }
            }
    
            return ret;
        }
    };

    But here (http://zhaohongze.com/wordpress/2013/12/10/leetcode-word-break-ii/) has a natural idea. We can still use DP - in the 2D dp array, at each slot, we can simply record multiple last slice indices :)

  • 相关阅读:
    android使用wcf接收上传图片视频文件
    android获取时间差的方法
    android JSON 技术
    Android LogCat使用详解
    VS2013菜单栏文字全大写的问题
    Mysql5.7安装配置
    解决Android Studio Gradle Build Running慢的问题
    Mysql创建用户并授权
    Windows 7 常用快捷键
    Python CRC16校验算法
  • 原文地址:https://www.cnblogs.com/tonix/p/3898536.html
Copyright © 2011-2022 走看看