Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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

posted on 2014-08-08 08:09  Tonix  阅读(183)  评论(0编辑  收藏  举报