<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>divide and conquer Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/divide-and-conquer/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/divide-and-conquer/</link>
	<description></description>
	<lastBuildDate>Sun, 01 Dec 2019 21:11:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>divide and conquer Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/divide-and-conquer/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1274. Number of Ships in a Rectangle</title>
		<link>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-1274-number-of-ships-in-a-rectangle/</link>
					<comments>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-1274-number-of-ships-in-a-rectangle/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Dec 2019 21:06:00 +0000</pubDate>
				<category><![CDATA[Divide and conquer]]></category>
		<category><![CDATA[divide and conquer]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[interactive]]></category>
		<category><![CDATA[quad tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5900</guid>

					<description><![CDATA[<p>(This problem is an&#160;interactive problem.) On the sea represented by a cartesian plane, each ship is located at an integer point, and each integer point&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-1274-number-of-ships-in-a-rectangle/">花花酱 LeetCode 1274. Number of Ships in a Rectangle</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p><em>(This problem is an&nbsp;<strong>interactive problem</strong>.)</em></p>



<p>On the sea represented by a cartesian plane, each ship is located at an integer point, and each integer point may contain at most 1 ship.</p>



<p>You have a function&nbsp;<code>Sea.hasShips(topRight, bottomLeft)</code>&nbsp;which takes two points&nbsp;as arguments and returns&nbsp;<code>true</code>&nbsp;if and only if there is at least one ship in the rectangle represented by the two points, including on the boundary.</p>



<p>Given two points, which are the top right and bottom left corners of a rectangle, return the number of ships present in that rectangle.&nbsp;&nbsp;It is guaranteed that there are&nbsp;<strong>at most 10 ships</strong>&nbsp;in that rectangle.</p>



<p>Submissions making&nbsp;<strong>more than 400 calls</strong>&nbsp;to&nbsp;<code>hasShips</code>&nbsp;will be judged&nbsp;<em>Wrong Answer</em>.&nbsp; Also, any solutions that attempt to circumvent the judge&nbsp;will result in disqualification.</p>



<p><strong>Example :</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/07/26/1445_example_1.PNG" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 
ships = [[1,1],[2,2],[3,3],[5,5]], topRight = [4,4], bottomLeft = [0,0]
<strong>Output:</strong> 3
<strong>Explanation:</strong> From [0,0] to [4,4] we can count 3 ships within the range.
</pre>



<p><strong>Constraints:</strong></p>



<ul><li>On the input&nbsp;<code>ships</code>&nbsp;is only given to initialize the map internally.&nbsp;You must solve this problem &#8220;blindfolded&#8221;. In other words, you must find the answer using the given&nbsp;<code>hasShips</code>&nbsp;API, without knowing the&nbsp;<code>ships</code>&nbsp;position.</li><li><code>0 &lt;=&nbsp;bottomLeft[0]&nbsp;&lt;= topRight[0]&nbsp;&lt;= 1000</code></li><li><code>0 &lt;=&nbsp;bottomLeft[1]&nbsp;&lt;= topRight[1]&nbsp;&lt;= 1000</code></li></ul>



<h2><strong>Solution: Divide and Conquer</strong></h2>



<p>If the current rectangle contains ships, subdivide it into 4 smaller ones until <br>1) no ships contained<br>2) the current rectangle is a single point (e.g. topRight == bottomRight)</p>



<p>Time complexity: O(logn)<br>Space complexity: O(logn)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  // Modify the interface to pass sea as a reference.
  int countShips(Sea&amp; sea, vector&lt;int&gt; topRight, vector&lt;int&gt; bottomLeft) {
    int x1 = bottomLeft[0], y1 = bottomLeft[1];
    int x2 = topRight[0], y2 = topRight[1];    
    if (x1 &gt; x2 || y1 &gt; y2 || !sea.hasShips(topRight, bottomLeft))
      return 0;
    if (x1 == x2 &amp;&amp; y1 == y2)
      return 1;
    int xm = x1 + (x2 - x1) / 2;
    int ym = y1 + (y2 - y1) / 2;
    return countShips(sea, {xm, ym}, {x1, y1}) + countShips(sea, {xm, y2}, {x1, ym + 1})
         + countShips(sea, {x2, ym}, {xm + 1, y1}) + countShips(sea, {x2, y2}, {xm + 1, ym + 1});
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-1274-number-of-ships-in-a-rectangle/">花花酱 LeetCode 1274. Number of Ships in a Rectangle</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-1274-number-of-ships-in-a-rectangle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 23. Merge k Sorted Lists</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists-2/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists-2/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 22 Jun 2019 19:46:36 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[divide and conquer]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[list]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5235</guid>

					<description><![CDATA[<p>Merge&#160;k&#160;sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ &#160; 1-&#62;4-&#62;5, &#160; 1-&#62;3-&#62;4, &#160; 2-&#62;6 ]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists-2/">花花酱 LeetCode 23. Merge k Sorted Lists</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe width="500" height="375" src="https://www.youtube.com/embed/XqA8bBoEdIY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Merge&nbsp;<em>k</em>&nbsp;sorted linked lists and return it as one sorted list. Analyze and describe its complexity.</p>



<p><strong>Example:</strong></p>



<pre class="wp-block-preformatted; crayon:false"><strong>Input:</strong>
[
&nbsp; 1-&gt;4-&gt;5,
&nbsp; 1-&gt;3-&gt;4,
&nbsp; 2-&gt;6
]
<strong>Output:</strong> 1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6</pre>



<h2><strong>Solution 1: Min heap</strong></h2>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/23-ep252.png" alt="" class="wp-image-5239" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/23-ep252.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/23-ep252-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/23-ep252-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Time complexity: O(nklogk)<br>Space complexity: O(k)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* mergeKLists(vector&lt;ListNode*&gt;&amp; lists) {
    ListNode dummy(0);
    ListNode *tail = &amp;dummy;
    
    auto comp = [](ListNode* a, ListNode* b) { return a-&gt;val &gt; b-&gt;val; };
    priority_queue&lt;ListNode*, vector&lt;ListNode*&gt;, decltype(comp)&gt; q(comp);
    
    for (ListNode* list : lists) 
      if (list) q.push(list);
    
    while (!q.empty()) {
      tail-&gt;next = q.top(); q.pop();      
      tail = tail-&gt;next;
      if (tail-&gt;next) q.push(tail-&gt;next);
    }
    return dummy.next;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Merge Sort</strong></h2>



<p>Time complexity: O(nklogk)<br>Space complexity: O(logk) </p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* mergeKLists(vector&lt;ListNode*&gt;&amp; lists) {
    return merge(lists, 0, lists.size() - 1);
  }
private:
  ListNode* merge(vector&lt;ListNode*&gt;&amp; lists, int l, int r) {
    if (l &gt; r) return nullptr;
    if (l == r) return lists[l];
    if (l + 1 == r) return mergeTwoLists(lists[l], lists[r]);
    int m = l + (r - l) / 2;
    auto l1 = merge(lists, l, m);
    auto l2 = merge(lists, m + 1, r);
    return mergeTwoLists(l1, l2);
  }
  ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    ListNode dummy(0);
    ListNode* tail = &amp;dummy;
    while (l1 &amp;&amp; l2) {
      if (l1-&gt;val &gt; l2-&gt;val) swap(l1, l2);                
      tail-&gt;next = l1;
      l1 = l1-&gt;next;
      tail = tail-&gt;next;
    }        
    if (l1) tail-&gt;next = l1;
    if (l2) tail-&gt;next = l2;        
    return dummy.next;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists-2/">花花酱 LeetCode 23. Merge k Sorted Lists</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-23-merge-k-sorted-lists-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 775. Global and Local Inversions</title>
		<link>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-775-global-and-local-inversions/</link>
					<comments>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-775-global-and-local-inversions/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 09 Jul 2018 15:31:50 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Divide and conquer]]></category>
		<category><![CDATA[divide and conquer]]></category>
		<category><![CDATA[inversion]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[mergesort]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3044</guid>

					<description><![CDATA[<p>Problem We have some permutation A of [0, 1, ..., N - 1], where N is the length of A. The number of (global) inversions is the number of i &#60; j with 0&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-775-global-and-local-inversions/">花花酱 LeetCode 775. Global and Local Inversions</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/3QHSJSFm0W0?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1>Problem</h1>
<p>We have some permutation <code>A</code> of <code>[0, 1, ..., N - 1]</code>, where <code>N</code> is the length of <code>A</code>.</p>
<p>The number of (global) inversions is the number of <code>i &lt; j</code> with <code>0 &lt;= i &lt; j &lt; N</code> and <code>A[i] &gt; A[j]</code>.</p>
<p>The number of local inversions is the number of <code>i</code> with <code>0 &lt;= i &lt; N</code> and <code>A[i] &gt; A[i+1]</code>.</p>
<p>Return <code>true</code> if and only if the number of global inversions is equal to the number of local inversions.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> A = [1,0,2]
<strong>Output:</strong> true
<strong>Explanation:</strong> There is 1 global inversion, and 1 local inversion.
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false "><strong>Input:</strong> A = [1,2,0]
<strong>Output:</strong> false
<strong>Explanation:</strong> There are 2 global inversions, and 1 local inversion.
</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>A</code> will be a permutation of <code>[0, 1, ..., A.length - 1]</code>.</li>
<li><code>A</code> will have length in range <code>[1, 5000]</code>.</li>
<li>The time limit for this problem has been reduced.</li>
</ul>
<h1>Solution1: Brute Force (TLE)</h1>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: TLE (208/208 test cases passed)
class Solution {
public:
  bool isIdealPermutation(vector&lt;int&gt;&amp; A) {
    const int n = A.size();
    int local = 0;
    for (int i = 0; i &lt; n - 1; ++i)
      if (A[i] &gt; A[i + 1]) ++local;
    int global = 0;
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        if (A[i] &gt; A[j] &amp;&amp; ++global &gt; local) return false;
    return global == local;
  }
};</pre><p>&nbsp;</p>
<h1>Solution2: MergeSort</h1>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 52 ms (&lt;96.42%)
class Solution {
public:
  bool isIdealPermutation(vector&lt;int&gt;&amp; A) {
    const int n = A.size();
    int local = 0;
    for (int i = 0; i &lt; n - 1; ++i)
      if (A[i] &gt; A[i + 1]) ++local;
    tmp = vector&lt;int&gt;(n);
    int global = mergeSort(A, 0, n - 1);
    return global == local;
  }
private:
  vector&lt;int&gt; tmp;
  int mergeSort(vector&lt;int&gt;&amp; A, int l, int r) {
    if (l &gt;= r) return 0;
    const int len = r - l + 1;
    int m = (r - l) / 2 + l;
    int inv = mergeSort(A, l, m) + mergeSort(A, m + 1, r);
        
    int i = l;
    int j = m + 1;
    int k = 0;
    
    while (i &lt;= m &amp;&amp; j &lt;= r) {
      if (A[i] &lt;= A[j]) {
        tmp[k++] = A[i++];
      } else {
        tmp[k++] = A[j++];
        inv += m - i + 1;
      }
    }
    
    while (i &lt;= m) tmp[k++] = A[i++];
    while (j &lt;= r) tmp[k++] = A[j++];
    
    std::copy(tmp.begin(), tmp.begin() + len, A.begin() + l);
    
    return inv;
  }
};</pre><p>C#</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 208 ms
public class Solution {
  public bool IsIdealPermutation(int[] A) {
    var n = A.Length;
    var localInv = 0;
    for (var i = 1; i &lt; n; ++i)
      if (A[i] &lt; A[i - 1]) ++localInv;
    tmp = new int[n];
    var globalInv = MergeSort(A, 0, n - 1);    
    return localInv == globalInv;
  }  
  private int[] tmp;  
  private int MergeSort(int[] A, int l, int r) {
    if (l &gt;= r) return 0;
    int m = (r - l) / 2 + l;
    int inv = MergeSort(A, l, m) + MergeSort(A, m + 1, r);
    int i = l;
    int j = m + 1;
    int k = 0;
    
    while (i &lt;= m &amp;&amp; j &lt;= r) {
      if (A[i] &lt;= A[j]) {
        tmp[k++] = A[i++];
      } else {
        inv += m - i + 1;
        tmp[k++] = A[j++];
      }
    }
    
    while (i &lt;= m) tmp[k++] = A[i++];
    while (j &lt;= r) tmp[k++] = A[j++];
    
    Array.Copy(tmp, 0, A, l, k);
    
    return inv;
  }
}</pre><p>&nbsp;</p>
<h1>Solution3: Input Property</h1>
<p>Input is a permutation of [0, 1, &#8230;, N &#8211; 1]</p>
<p>Time Complexity: O(n)</p>
<p>Space Complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 40 ms (&lt;99.26%)
class Solution {
public:
  bool isIdealPermutation(vector&lt;int&gt;&amp; A) {
    for (int i = 0; i &lt; A.size(); ++i)
        if (abs(A[i] - i) &gt; 1) return false;
	  return true;
  }
};</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-775-global-and-local-inversions/">花花酱 LeetCode 775. Global and Local Inversions</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/divide-and-conquer/leetcode-775-global-and-local-inversions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 856. Score of Parentheses</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 27 Jun 2018 04:16:13 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[balance]]></category>
		<category><![CDATA[divide and conquer]]></category>
		<category><![CDATA[stack]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2934</guid>

					<description><![CDATA[<p>Problem Given a balanced parentheses string S, compute the score of the string based on the following rule: () has score 1 AB has score A + B, where&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/">花花酱 LeetCode 856. Score of Parentheses</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/tiAaVfMcL9w?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given a balanced parentheses string <code>S</code>, compute the score of the string based on the following rule:</p>
<ul>
<li><code>()</code> has score 1</li>
<li><code>AB</code> has score <code>A + B</code>, where A and B are balanced parentheses strings.</li>
<li><code>(A)</code> has score <code>2 * A</code>, where A is a balanced parentheses string.</li>
</ul>
<p>&nbsp;</p>
<div>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">"()"</span>
<strong>Output: </strong><span id="example-output-1">1</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-2-1">"(())"</span>
<strong>Output: </strong><span id="example-output-2">2</span>
</pre>
<div>
<p><strong>Example 3:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-3-1">"()()"</span>
<strong>Output: </strong><span id="example-output-3">2</span>
</pre>
<div>
<p><strong>Example 4:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-4-1">"(()(()))"</span>
<strong>Output: </strong><span id="example-output-4">6</span>
</pre>
<h1></h1>
<h1><img class="alignnone size-full wp-image-2941" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></h1>
<h1><img class="alignnone size-full wp-image-2940" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/06/856-ep198-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></h1>
<h1>Solution1: Recursion</h1>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4ms
class Solution {
public:
  int scoreOfParentheses(string S) {
    return score(S, 0, S.length() - 1);
  }
private:
  int score(const string&amp; S, int l, int r) {    
    if (r - l == 1) return 1; // "()"
    int b = 0;
    for (int i = l; i &lt; r; ++i) {
      if (S[i] == '(') ++b;
      if (S[i] == ')') --b;
      if (b == 0) // balanced
        // score("(A)(B)") = score("(A)") + score("(B)")
        return score(S, l, i) + score(S, i + 1, r);    
    }
    // score("(A)") = 2 * score("A")
    return 2 * score(S, l + 1, r - 1); 
  }
};</pre><p>&nbsp;</p>
<h1><strong>Solution2: Counting</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  int scoreOfParentheses(string S) {
    int ans = 0;
    int d = -1;
    for (int i = 0; i &lt; S.length(); ++i) {
      d += S[i] == '(' ? 1 : -1;
      if (S[i] == '(' &amp;&amp; S[i + 1] == ')')
        ans += 1 &lt;&lt; d;
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
</div>
</div>
</div>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/">花花酱 LeetCode 856. Score of Parentheses</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-856-score-of-parentheses/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
