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 :)

  • 相关阅读:
    C++库---json
    C++之单例模式
    mysql之字段(整形、字符串等)
    C++之数据类型,容器
    C++文件操作,判断两个文件内容是否相等(被修改)
    (转)mysql之index(索引)
    Django中的日期和时间格式 DateTimeField
    有关Django的smallDemo
    mysql 快速生成百万条测试数据
    从输入URL到页面加载发生了什么
  • 原文地址:https://www.cnblogs.com/tonix/p/3898536.html
Copyright © 2011-2022 走看看