{"id":60,"date":"2017-09-03T22:34:28","date_gmt":"2017-09-04T05:34:28","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=60"},"modified":"2018-09-18T23:18:08","modified_gmt":"2018-09-19T06:18:08","slug":"leetcode-241-different-ways-to-add-parentheses","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/leetcode\/leetcode-241-different-ways-to-add-parentheses\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 241. Different Ways to Add Parentheses"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 241. Different Ways to Add Parentheses - \u5237\u9898\u627e\u5de5\u4f5c EP32\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/gxYV8eZY0eQ?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<p>Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are\u00a0<code>+<\/code>,\u00a0<code>-<\/code>\u00a0and\u00a0<code>*<\/code>.<\/p>\n<p><strong>Example 1:<\/strong><\/p>\n<p>Input:\u00a0<code>\"2-1-1\"<\/code>.<\/p>\n<pre class=\"\">((2-1)-1) = 0\r\n(2-(1-1)) = 2<\/pre>\n<p>Output:\u00a0<code>[0, 2]<\/code><\/p>\n<p><strong>Example 2:<\/strong><\/p>\n<p>Input:\u00a0<code>\"2*3-4*5\"<\/code><\/p>\n<pre class=\"\">(2*(3-(4*5))) = -34\r\n((2*3)-(4*5)) = -14\r\n((2*(3-4))*5) = -10\r\n(2*((3-4)*5)) = -10\r\n(((2*3)-4)*5) = 10<\/pre>\n<p>Output:\u00a0<code>[-34, -14, -10, -10, 10]<\/code><\/p>\n<p><strong>Solution:<\/strong><\/p>\n<p>Running time: 3ms<\/p>\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:c++ decode:true\">\/\/ Author: Huahua\r\nnamespace huahua {\r\n    int add(int a, int b) { return a+b; }\r\n    int minus(int a, int b) { return a-b; }\r\n    int multiply(int a, int b) { return a*b; }\r\n} \/\/ namespace huahua\r\n\r\nclass Solution {\r\npublic:\r\n    vector&lt;int&gt; diffWaysToCompute(string input) {\r\n        return ways(input);\r\n    }\r\nprivate:    \r\n    \r\n    const vector&lt;int&gt;&amp; ways(const string&amp; input) {\r\n        \/\/ Already solved, return the answer\r\n        if(m_.count(input)) return m_[input];\r\n        \r\n        \/\/ Array for answer of input\r\n        vector&lt;int&gt; ans;\r\n        \r\n        \/\/ Break the expression at every operator\r\n        for(int i=0;i&lt;input.length();++i) {\r\n            char op = input[i];\r\n            \/\/ Split the input by an op\r\n            if(op=='+' || op=='-' || op=='*') {\r\n                const string left = input.substr(0, i);\r\n                const string right = input.substr(i+1);\r\n                \/\/ Get the solution of left\/right sub-expressions\r\n                const vector&lt;int&gt;&amp; l = ways(left);\r\n                const vector&lt;int&gt;&amp; r = ways(right);\r\n                \r\n                std::function&lt;int(int,int)&gt; f;\r\n                \r\n                switch(op) {\r\n                    case '+': f = huahua::add; break;\r\n                    case '-': f = huahua::minus; break;\r\n                    case '*': f = huahua::multiply; break;\r\n                }\r\n                \r\n                \/\/ Combine the solution\r\n                for(int a : l)\r\n                    for(int b : r) \r\n                        ans.push_back(f(a,b));\r\n            }\r\n        }\r\n        \r\n        \/\/ Single number, e.g. s = \"3\"\r\n        if(ans.empty())\r\n            ans.push_back(std::stoi(input));\r\n        \r\n        \/\/ memorize the answer for input\r\n        m_[input].swap(ans);\r\n        return m_[input];\r\n    }\r\n    \r\n    unordered_map&lt;string, vector&lt;int&gt;&gt; m_;\r\n};<\/pre>\n\n<\/div><h2 class=\"tabtitle\">Python3<\/h2>\n<div class=\"tabcontent\">\n\n<pre class=\"lang:python decode:true \"># Author: Huahua, 44 ms\r\nclass Solution:\r\n  def diffWaysToCompute(self, input):    \r\n    ops = {'+': lambda x, y: x + y,\r\n           '-': lambda x, y: x - y,\r\n           '*': lambda x, y: x * y}\r\n    def ways(s):\r\n      ans = []\r\n      for i in range(len(s)):\r\n        if s[i] in \"+-*\":          \r\n          ans += [ops[s[i]](l, r) for l, r in itertools.product(ways(s[0:i]), ways(s[i+1:]))]\r\n      if not ans: ans.append(int(s))\r\n      return ans\r\n    return ways(input)<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid&#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":[31,17,4],"class_list":["post-60","post","type-post","status-publish","format-standard","hentry","category-dynamic-programming","category-leetcode","tag-math","tag-recursion","tag-string","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/60","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=60"}],"version-history":[{"count":8,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/60\/revisions"}],"predecessor-version":[{"id":4031,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/60\/revisions\/4031"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=60"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=60"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=60"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}