{"id":52,"date":"2017-09-02T19:22:43","date_gmt":"2017-09-03T00:22:43","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=52"},"modified":"2018-08-28T23:07:24","modified_gmt":"2018-08-29T06:07:24","slug":"leetcode-140-word-break-ii","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/leetcode\/leetcode-140-word-break-ii\/","title":{"rendered":"\u82b1\u82b1\u9171 Leetcode 140. Word Break II"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 140. Word Break II - \u5237\u9898\u627e\u5de5\u4f5c -  EP29\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/JqOIRBC0_9c?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h1><strong>Problem<\/strong><\/h1>\n<p>Given a\u00a0<b>non-empty<\/b>\u00a0string\u00a0<i>s<\/i>\u00a0and a dictionary\u00a0<i>wordDict<\/i>\u00a0containing a list of\u00a0<b>non-empty<\/b>\u00a0words, add spaces in\u00a0<i>s<\/i>\u00a0to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.<\/p>\n<p>Return all such possible sentences.<\/p>\n<p>For example, given<br \/>\n<i>s<\/i>\u00a0=\u00a0<code>\"catsanddog\"<\/code>,<br \/>\n<i>dict<\/i>\u00a0=\u00a0<code>[\"cat\", \"cats\", \"and\", \"sand\", \"dog\"]<\/code>.<\/p>\n<p>A solution is\u00a0<code>[\"cats and dog\", \"cat sand dog\"]<\/code>.<\/p>\n<p><b><span style=\"color: red;\">UPDATE (2017\/1\/4):<\/span><\/b><br \/>\nThe\u00a0<i>wordDict<\/i>\u00a0parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.<\/p>\n<h1><strong>Solution<\/strong><\/h1>\n<p>Time complexity: O(2^n)<\/p>\n<p>Space complexity: O(2^n)<\/p>\n<p>C++<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\nclass Solution {\r\npublic:\r\n    vector&lt;string&gt; wordBreak(string s, vector&lt;string&gt;&amp; wordDict) {\r\n        unordered_set&lt;string&gt; dict(wordDict.cbegin(), wordDict.cend());\r\n        return wordBreak(s, dict);\r\n    }\r\nprivate:\r\n    \/\/ &gt;&gt; append({\"cats and\", \"cat sand\"}, \"dog\");\r\n    \/\/ {\"cats and dog\", \"cat sand dog\"}\r\n    vector&lt;string&gt; append(const vector&lt;string&gt;&amp; prefixes, const string&amp; word) {\r\n        vector&lt;string&gt; results;\r\n        for(const auto&amp; prefix : prefixes)\r\n            results.push_back(prefix + \" \" + word);\r\n        return results;\r\n    }\r\n    \r\n    const vector&lt;string&gt;&amp; wordBreak(string s, unordered_set&lt;string&gt;&amp; dict) {\r\n        \/\/ Already in memory, return directly\r\n        if(mem_.count(s)) return mem_[s];\r\n        \r\n        \/\/ Answer for s\r\n        vector&lt;string&gt; ans;\r\n        \r\n        \/\/ s in dict, add it to the answer array\r\n        if(dict.count(s)) \r\n            ans.push_back(s);\r\n        \r\n        for(int j=1;j&lt;s.length();++j) {\r\n            \/\/ Check whether right part is a word\r\n            const string&amp; right = s.substr(j);\r\n            if (!dict.count(right)) continue;\r\n            \r\n            \/\/ Get the ans for left part\r\n            const string&amp; left = s.substr(0, j);\r\n            const vector&lt;string&gt; left_ans = \r\n                append(wordBreak(left, dict), right);\r\n            \r\n            \/\/ Notice, can not use mem_ here,\r\n            \/\/ since we haven't got the ans for s yet.\r\n            ans.insert(ans.end(), left_ans.begin(), left_ans.end());\r\n        }\r\n        \r\n        \/\/ memorize and return\r\n        mem_[s].swap(ans);\r\n        return mem_[s];\r\n    }\r\nprivate:\r\n    unordered_map&lt;string, vector&lt;string&gt;&gt; mem_;\r\n};<\/pre>\n<p>Python3<\/p>\n<pre class=\"lang:default decode:true \">\"\"\"\r\nAuthor: Huahua\r\nRunning time: 56 ms\r\n\"\"\"\r\nclass Solution:\r\n  def wordBreak(self, s, wordDict):\r\n    words = set(wordDict)\r\n    mem = {}\r\n    def wordBreak(s):\r\n      if s in mem: return mem[s]\r\n      ans = []\r\n      if s in words: ans.append(s)\r\n      for i in range(1, len(s)):\r\n        right = s[i:]\r\n        if right not in words: continue        \r\n        ans += [w + \" \" + right for w in wordBreak(s[0:i])]\r\n      mem[s] = ans\r\n      return mem[s]\r\n    return wordBreak(s)<\/pre>\n<p>&nbsp;<\/p>\n<h1><strong>Related Problems<\/strong><\/h1>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/leetcode\/leetcode-139-word-break\/\">[\u89e3\u9898\u62a5\u544a] Leetcode 139. Word Break \u82b1\u82b1\u9171<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/searching\/127-word-ladder\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 127. Word Ladder<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/searching\/leetcode-126-word-ladder-ii\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 126. Word Ladder II<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem Given a\u00a0non-empty\u00a0string\u00a0s\u00a0and a dictionary\u00a0wordDict\u00a0containing a list of\u00a0non-empty\u00a0words, add spaces in\u00a0s\u00a0to construct a sentence where each word is a valid dictionary word. You may assume&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[46,3],"tags":[122,26,217,29],"class_list":["post-52","post","type-post","status-publish","format-standard","hentry","category-dynamic-programming","category-leetcode","tag-combination","tag-dynamic-programming","tag-hard","tag-word-break","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/52","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=52"}],"version-history":[{"count":9,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/52\/revisions"}],"predecessor-version":[{"id":3746,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/52\/revisions\/3746"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=52"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=52"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=52"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}