zoukankan      html  css  js  c++  java
  • [LeetCode] Word Break II (TLE)

    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"].

    这题没有AC,但是做出了递归回朔的版本,最后一个一串a后面跟个b的case超时了没法通过。

                                                    sand -- [dog] ->"cat sand dog"

                                                  /

                           cat --[sanddog] 

                         /                   

    [catsanddog]                       

                         

                           cats --[anddog]

                                                 

                                                    and -- [dog] -> "cats and dog"

    从这个结构可以看出,这个问题可以被分解为当前的问题+更小规模的同类子问题,用递归求解。

    我用了一个vector<stirng>来记录每个阶段(路径)上的结果,当搜索完字符串的时候(left >= right)意味着数组里的就是一个结果。

    void wb(string s, int left, int right, unordered_set<string> &dict, vector<string> t,  vector<string> &re) {
        if (s.length() <= 0)
            return;
        if (left >= right) {
            string k;
            for (int i=0; i<t.size(); i++) {
                if (i != t.size()-1) {
                    k = k + t[i] + " ";
                }
                else
                    k+=t[i];
            }
            re.push_back(k);
            return;
        }
        //find matches
        for (const auto& elem: dict) {
            int len = (int)((string)elem).size();
            if (left+len > s.length()) continue;
            string sub = s.substr(left, len);
            if (elem.compare(sub) == 0) {
                t.push_back(sub);
                wb(s, left+len, right, dict, t, re);
                if (t.size())
                    t.pop_back();
            }
        }
    }
    
    vector<string> wordBreak(string s,  unordered_set<string> &dict) {
        vector<string> ret;
        vector<string> t;
        wb(s, 0, s.size()-1, dict,t, ret);
        return ret;
    }

    在编写过程中遇到的两个bug都是因为没有很好理解程序造成的,第一个是t数组,一开始我传起引用,结果发现最后结果集翻倍。。。 第二个是调用wb后 t 没有pop,这样就把前一个分支的内容带到了下一分支造成错乱。

    求大神指导如何AC

  • 相关阅读:
    A. Greg and Array 夜
    zoj 2314 Reactor Cooling 夜
    sgu 104. Little shop of flowers 夜
    C. Greg and Friends 夜
    sgu 103. Traffic Lights 夜
    B. Greg and Graph 夜
    B. Yaroslav and Two Strings 夜
    zoj 2313 Chinese Girls' Amusement 夜
    sgu 101. Domino 夜
    hdu 4532 湫秋系列故事——安排座位 夜
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4047931.html
Copyright © 2011-2022 走看看