<?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>DFS Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/dfs/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/dfs/</link>
	<description></description>
	<lastBuildDate>Sun, 13 Oct 2024 05:04:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.9</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>DFS Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/dfs/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Oct 2024 05:02:58 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[binary tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[perfect tree]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10188</guid>

					<description><![CDATA[<p>You are given the&#160;root&#160;of a&#160;binary tree&#160;and an integer&#160;k. Return an integer denoting the size of the&#160;kth&#160;largest&#160;perfect binary&#160; subtree, or&#160;-1&#160;if it doesn&#8217;t exist. A&#160;perfect binary tree&#160;is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/">花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</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>You are given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>binary tree</strong>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>Return an integer denoting the size of the&nbsp;<code>k<sup>th</sup></code>&nbsp;<strong>largest<em>&nbsp;</em>perfect binary</strong><em>&nbsp;</em></p>



<p>subtree, or&nbsp;<code>-1</code>&nbsp;if it doesn&#8217;t exist.</p>



<p>A&nbsp;<strong>perfect binary tree</strong>&nbsp;is a tree where all leaves are on the same level, and every parent has two children.</p>



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



<p><strong>Input:</strong>&nbsp;root = [5,3,6,5,2,5,7,1,8,null,null,6,8], k = 2</p>



<p><strong>Output:</strong>&nbsp;3</p>



<p><strong>Explanation:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2024/06/21/image.jpg" alt=""/></figure>



<p>The roots of the perfect binary subtrees are highlighted in black. Their sizes, in decreasing order are&nbsp;<code>[3, 3, 1, 1, 1, 1, 1, 1]</code>.<br>The&nbsp;<code>2<sup>nd</sup></code>&nbsp;largest size is 3.</p>



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



<p><strong>Input:</strong>&nbsp;root = [1,2,3,4,5,6,7], k = 1</p>



<p><strong>Output:</strong>&nbsp;7</p>



<p><strong>Explanation:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2024/06/21/image1.jpg" alt=""/></figure>



<p>The sizes of the perfect binary subtrees in decreasing order are&nbsp;<code>[7, 3, 3, 1, 1, 1, 1]</code>. The size of the largest perfect binary subtree is 7.</p>



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



<p><strong>Input:</strong>&nbsp;root = [1,2,3,null,4], k = 3</p>



<p><strong>Output:</strong>&nbsp;-1</p>



<p><strong>Explanation:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2024/06/21/image4.jpg" alt=""/></figure>



<p>The sizes of the perfect binary subtrees in decreasing order are&nbsp;<code>[1, 1]</code>. There are fewer than 3 perfect binary subtrees.</p>



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



<ul><li>The number of nodes in the tree is in the range <code>[1, 2000]</code>.</li><li><code>1 &lt;= Node.val &lt;= 2000</code></li><li><code>1 &lt;= k &lt;= 1024</code></li></ul>



<h2><strong>Solution: DFS</strong></h2>



<p>Write a function f() to return the perfect subtree size at node n.</p>



<p>def f(TreeNode n):<br>  if not n: return 0<br>  l, r = f(n.left), f(n.right)<br>  return l + r + 1 if l == r &amp;&amp; l != -1 else -1</p>



<p>Time complexity: O(n + KlogK)<br>Space complexity: O(n)</p>



<pre class="crayon-plain-tag">class Solution {
public:
  int kthLargestPerfectSubtree(TreeNode* root, int k) {
    vector&amp;lt;int&gt; ss;
    function&amp;lt;int(TreeNode*)&gt; PerfectSubtree = &amp;#91;&amp;amp;](TreeNode* node) -&gt; int {
      if (node == nullptr) return 0;
      int l = PerfectSubtree(node-&gt;left);
      int r = PerfectSubtree(node-&gt;right);
      if (l == r &amp;amp;&amp;amp; l != -1) {
        ss.push_back(l + r + 1);
        return ss.back();
      }
      return -1;  
    };
    PerfectSubtree(root);
    sort(rbegin(ss), rend(ss));
    return k &amp;lt;= ss.size() ? ss&amp;#91;k - 1] : -1;
  }
};</pre>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/">花花酱 LeetCode 3319. K-th Largest Perfect Subtree Size in Binary Tree</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/tree/leetcode-3319-k-th-largest-perfect-subtree-size-in-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2658. Maximum Number of Fish in a Grid</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2658-maximum-number-of-fish-in-a-grid/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2658-maximum-number-of-fish-in-a-grid/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 15:30:49 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[connected components]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10032</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;2D matrix&#160;grid&#160;of size&#160;m x n, where&#160;(r, c)&#160;represents: A&#160;land&#160;cell if&#160;grid[r][c] = 0, or A&#160;water&#160;cell containing&#160;grid[r][c]&#160;fish, if&#160;grid[r][c] &#62; 0. A fisher can start at&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2658-maximum-number-of-fish-in-a-grid/">花花酱 LeetCode 2658. Maximum Number of Fish in a Grid</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;2D matrix&nbsp;<code>grid</code>&nbsp;of size&nbsp;<code>m x n</code>, where&nbsp;<code>(r, c)</code>&nbsp;represents:</p>



<ul><li>A&nbsp;<strong>land</strong>&nbsp;cell if&nbsp;<code>grid[r][c] = 0</code>, or</li><li>A&nbsp;<strong>water</strong>&nbsp;cell containing&nbsp;<code>grid[r][c]</code>&nbsp;fish, if&nbsp;<code>grid[r][c] &gt; 0</code>.</li></ul>



<p>A fisher can start at any&nbsp;<strong>water</strong>&nbsp;cell&nbsp;<code>(r, c)</code>&nbsp;and can do the following operations any number of times:</p>



<ul><li>Catch all the fish at cell&nbsp;<code>(r, c)</code>, or</li><li>Move to any adjacent&nbsp;<strong>water</strong>&nbsp;cell.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of fish the fisher can catch if he chooses his starting cell optimally, or&nbsp;</em><code>0</code>&nbsp;if no water cell exists.</p>



<p>An&nbsp;<strong>adjacent</strong>&nbsp;cell of the cell&nbsp;<code>(r, c)</code>, is one of the cells&nbsp;<code>(r, c + 1)</code>,&nbsp;<code>(r, c - 1)</code>,&nbsp;<code>(r + 1, c)</code>&nbsp;or&nbsp;<code>(r - 1, c)</code>&nbsp;if it exists.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2023/03/29/example.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[0,2,1,0],[4,0,0,3],[1,0,0,4],[0,3,2,0]]
<strong>Output:</strong> 7
<strong>Explanation:</strong> The fisher can start at cell <code>(1,3)</code> and collect 3 fish, then move to cell <code>(2,3)</code>&nbsp;and collect 4 fish.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2023/03/29/example2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,1]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The fisher can start at cells (0,0) or (3,3) and collect a single fish. 
</pre>



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



<ul><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 10</code></li><li><code>0 &lt;= grid[i][j] &lt;= 10</code></li></ul>



<h2><strong>Solution: Connected Component</strong></h2>



<p>Similar to <a href="https://zxi.mytechroad.com/blog/graph/leetcode-695-max-area-of-island/">花花酱 LeetCode 695. Max Area of Island</a></p>



<p>Find the connected component that has the max sum.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int findMaxFish(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    function&lt;int(int, int)&gt; dfs = [&amp;](int r, int c) {
      if (r &lt; 0 || r &gt;= m || c &lt; 0 || c &gt;= n || !grid[r][c]) return 0;      
      return exchange(grid[r][c], 0) 
        + dfs(r - 1, c) + dfs(r, c - 1) + dfs(r + 1, c) + dfs(r, c + 1);
    };
    int ans = 0;
    for (int r = 0; r &lt; m; ++r)
      for (int c = 0; c &lt; n; ++c)
        ans = max(ans, dfs(r, c));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2658-maximum-number-of-fish-in-a-grid/">花花酱 LeetCode 2658. Maximum Number of Fish in a Grid</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/graph/leetcode-2658-maximum-number-of-fish-in-a-grid/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Mar 2023 15:51:10 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sorting]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9973</guid>

					<description><![CDATA[<p>You are given the&#160;root&#160;of a binary tree and a positive integer&#160;k. The&#160;level sum&#160;in the tree is the sum of the values of the nodes that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/">花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</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>You are given the&nbsp;<code>root</code>&nbsp;of a binary tree and a positive integer&nbsp;<code>k</code>.</p>



<p>The&nbsp;<strong>level sum</strong>&nbsp;in the tree is the sum of the values of the nodes that are on the&nbsp;<strong>same</strong>&nbsp;level.</p>



<p>Return<em>&nbsp;the&nbsp;</em><code>k<sup>th</sup></code><em>&nbsp;<strong>largest</strong>&nbsp;level sum in the tree (not necessarily distinct)</em>. If there are fewer than&nbsp;<code>k</code>&nbsp;levels in the tree, return&nbsp;<code>-1</code>.</p>



<p><strong>Note</strong>&nbsp;that two nodes are on the same level if they have the same distance from the root.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/12/14/binaryytreeedrawio-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [5,8,9,2,1,3,7,4,6], k = 2
<strong>Output:</strong> 13
<strong>Explanation:</strong> The level sums are the following:
- Level 1: 5.
- Level 2: 8 + 9 = 17.
- Level 3: 2 + 1 + 3 + 7 = 13.
- Level 4: 4 + 6 = 10.
The 2<sup>nd</sup> largest level sum is 13.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/12/14/treedrawio-3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [1,2,null,3], k = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest level sum is 3.
</pre>



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



<ul><li>The number of nodes in the tree is&nbsp;<code>n</code>.</li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= Node.val &lt;= 10<sup>6</sup></code></li><li><code>1 &lt;= k &lt;= n</code></li></ul>



<h2><strong>Solution: DFS + Sorting</strong></h2>



<p>Use DFS to traverse the tree and accumulate level sum. Once done, sort the level sums and find the k-th largest one.</p>



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



<p>Note: sum can be very large, use long long.</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long kthLargestLevelSum(TreeNode* root, int k) {
    vector&lt;long long&gt; sums;
    function&lt;void(TreeNode*, int)&gt; dfs = [&amp;](TreeNode* root, int d) {
      if (!root) return;
      while (d &gt;= sums.size()) sums.push_back(0);
      sums[d] += root-&gt;val;
      dfs(root-&gt;left, d + 1);
      dfs(root-&gt;right, d + 1);
    };
    dfs(root, 0);
    if (sums.size() &lt; k) return -1;
    sort(rbegin(sums), rend(sums));
    return sums[k - 1];
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/">花花酱 LeetCode 2583. Kth Largest Sum in a Binary Tree</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/tree/leetcode-2583-kth-largest-sum-in-a-binary-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2477. Minimum Fuel Cost to Report to the Capital</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 26 Nov 2022 16:41:02 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9905</guid>

					<description><![CDATA[<p>There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of&#160;n&#160;cities numbered from&#160;0&#160;to&#160;n - 1&#160;and exactly&#160;n - 1&#160;roads. The&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/">花花酱 LeetCode 2477. Minimum Fuel Cost to Report to the Capital</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>There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of&nbsp;<code>n</code>&nbsp;cities numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;and exactly&nbsp;<code>n - 1</code>&nbsp;roads. The capital city is city&nbsp;<code>0</code>. You are given a 2D integer array&nbsp;<code>roads</code>&nbsp;where&nbsp;<code>roads[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>&nbsp;denotes that there exists a&nbsp;<strong>bidirectional road</strong>&nbsp;connecting cities&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>.</p>



<p>There is a meeting for the representatives of each city. The meeting is in the capital city.</p>



<p>There is a car in each city. You are given an integer&nbsp;<code>seats</code>&nbsp;that indicates the number of seats in each car.</p>



<p>A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.</p>



<p>Return&nbsp;<em>the minimum number of liters of fuel to reach the capital city</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/09/22/a4c380025e3ff0c379525e96a7d63a3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [[0,1],[0,2],[0,3]], seats = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong> 
- Representative<sub>1</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>2</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>3</sub> goes directly to the capital with 1 liter of fuel.
It costs 3 liters of fuel at minimum. 
It can be proven that 3 is the minimum number of liters of fuel needed.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/11/16/2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> 
- Representative<sub>2</sub> goes directly to city 3 with 1 liter of fuel.
- Representative<sub>2</sub> and representative<sub>3</sub> go together to city 1 with 1 liter of fuel.
- Representative<sub>2</sub> and representative<sub>3</sub> go together to the capital with 1 liter of fuel.
- Representative<sub>1</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>5</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>6</sub> goes directly to city 4 with 1 liter of fuel.
- Representative<sub>4</sub> and representative<sub>6</sub> go together to the capital with 1 liter of fuel.
It costs 7 liters of fuel at minimum. 
It can be proven that 7 is the minimum number of liters of fuel needed.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/09/27/efcf7f7be6830b8763639cfd01b690a.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [], seats = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No representatives need to travel to the capital city.
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>roads.length == n - 1</code></li><li><code>roads[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt; n</code></li><li><code>a<sub>i</sub>&nbsp;!= b<sub>i</sub></code></li><li><code>roads</code>&nbsp;represents a valid tree.</li><li><code>1 &lt;= seats &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Greedy + DFS</strong></h2>



<p>To reach the minimum cost, we must share cars if possible, say X reps from children nodes to an intermediate node u on the way towards capital 0.  Then they all changes cars at node u, and we need (X + 1) // seats cars/fuel from u to 0.</p>



<p>We use DFS to count # of reps at each node u while accumulating the total cost.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long minimumFuelCost(vector&lt;vector&lt;int&gt;&gt;&amp; roads, int seats) {
    long long ans = 0;
    vector&lt;vector&lt;int&gt;&gt; g(roads.size() + 1);
    for (const vector&lt;int&gt;&amp; r : roads) {
      g[r[0]].push_back(r[1]);
      g[r[1]].push_back(r[0]);
    }
    // Returns total # of children of u.
    function&lt;int(int, int)&gt; dfs = [&amp;](int u, int p, int rep = 1) {      
      for (int v : g[u])
        if (v != p) rep += dfs(v, u);
      if (u) ans += (rep + seats - 1) / seats;
      return rep;
    };
    dfs(0, -1);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/">花花酱 LeetCode 2477. Minimum Fuel Cost to Report to the Capital</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/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2316. Count Unreachable Pairs of Nodes in an Undirected Graph</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Jun 2022 23:07:42 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[union find]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9761</guid>

					<description><![CDATA[<p>You are given an integer n. There is an undirected graph with n nodes, numbered from 0 to n - 1. You are given a 2D integer array edges where edges[i] = [ai, bi] denotes that there&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/">花花酱 LeetCode 2316. Count Unreachable Pairs of Nodes in an Undirected Graph</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 is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2316. Count Unreachable Pairs of Nodes in an Undirected Graph - 刷题找工作 EP397" width="500" height="281" src="https://www.youtube.com/embed/vH9CLfE82Rk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given an integer <code>n</code>. There is an <strong>undirected</strong> graph with <code>n</code> nodes, numbered from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> denotes that there exists an <strong>undirected</strong> edge connecting nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>number of pairs</strong>&nbsp;of different nodes that are&nbsp;<strong>unreachable</strong>&nbsp;from each other</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/05/05/tc-3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, edges = [[0,1],[0,2],[1,2]]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no pairs of nodes that are unreachable from each other. Therefore, we return 0.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/05/05/tc-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]]
<strong>Output:</strong> 14
<strong>Explanation:</strong> There are 14 pairs of nodes that are unreachable from each other:
[[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]].
Therefore, we return 14.
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= edges.length &lt;= 2 * 10<sup>5</sup></code></li><li><code>edges[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt; n</code></li><li><code>a<sub>i</sub>&nbsp;!= b<sub>i</sub></code></li><li>There are no repeated edges.</li></ul>



<h2><strong>Solution 1: DFS</strong></h2>



<p>Use DFS to find all CCs</p>



<p>Time complexity: O(V+E)<br>Space complexity: O(V+E)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
// Author: Huahua, 791ms, 136 MB
class Solution {
public:
  long long countPairs(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    vector&lt;vector&lt;int&gt;&gt; g(n);
    for (const auto&amp; e : edges) {
      g[e[0]].push_back(e[1]);
      g[e[1]].push_back(e[0]);
    }
    vector&lt;int&gt; seen(n);
    long long cur = 0;
    
    function&lt;void(int)&gt; dfs = [&amp;](int u) {
      ++cur;
      for (int v : g[u])
        if (seen[v]++ == 0) dfs(v);      
    };
    long long ans = 0;    
    for (int i = 0; i &lt; n; ++i) {
      if (seen[i]++) continue;
      cur = 0;
      dfs(i);
      ans += (n - cur) * cur;
    }
    return ans / 2;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Union Find</strong></h2>



<p>Time complexity: O(V+E)<br>Space complexity: O(V)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long countPairs(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    vector&lt;int&gt; parents(n);
    vector&lt;int&gt; counts(n, 1);
    std::iota(begin(parents), end(parents), 0);
    
    function&lt;int(int)&gt; find = [&amp;](int x) {
      if (parents[x] == x) return x;
      return parents[x] = find(parents[x]);
    };
    
    for (const auto&amp; e : edges) {
      int ru = find(e[0]);
      int rv = find(e[1]);
      if (ru != rv) {
        parents[rv] = ru;
        counts[ru] += counts[rv];        
      }
    }
    long long ans = 0;    
    for (int i = 0; i &lt; n; ++i)      
      ans += n - counts[find(i)];
    return ans / 2;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/">花花酱 LeetCode 2316. Count Unreachable Pairs of Nodes in an Undirected Graph</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/graph/leetcode-2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 12 Mar 2022 07:14:40 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9570</guid>

					<description><![CDATA[<p>You are given a positive integer&#160;n&#160;representing the number of nodes of a&#160;Directed Acyclic Graph&#160;(DAG). The nodes are numbered from&#160;0&#160;to&#160;n - 1&#160;(inclusive). You are also given&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/">花花酱 LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph</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>You are given a positive integer&nbsp;<code>n</code>&nbsp;representing the number of nodes of a&nbsp;<strong>Directed Acyclic Graph</strong>&nbsp;(DAG). The nodes are numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;(<strong>inclusive</strong>).</p>



<p>You are also given a 2D integer array&nbsp;<code>edges</code>, where&nbsp;<code>edges[i] = [from<sub>i</sub>, to<sub>i</sub>]</code>&nbsp;denotes that there is a&nbsp;<strong>unidirectional</strong>&nbsp;edge from&nbsp;<code>from<sub>i</sub></code>&nbsp;to&nbsp;<code>to<sub>i</sub></code>&nbsp;in the graph.</p>



<p>Return&nbsp;<em>a list</em>&nbsp;<code>answer</code><em>, where&nbsp;</em><code>answer[i]</code><em>&nbsp;is the&nbsp;<strong>list of ancestors</strong>&nbsp;of the</em>&nbsp;<code>i<sup>th</sup></code>&nbsp;<em>node, sorted in&nbsp;<strong>ascending order</strong></em>.</p>



<p>A node&nbsp;<code>u</code>&nbsp;is an&nbsp;<strong>ancestor</strong>&nbsp;of another node&nbsp;<code>v</code>&nbsp;if&nbsp;<code>u</code>&nbsp;can reach&nbsp;<code>v</code>&nbsp;via a set of edges.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/12/e1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 8, edgeList = [[0,3],[0,4],[1,3],[2,4],[2,7],[3,5],[3,6],[3,7],[4,6]]
<strong>Output:</strong> [[],[],[],[0,1],[0,2],[0,1,3],[0,1,2,3,4],[0,1,2,3]]
<strong>Explanation:</strong>
The above diagram represents the input graph.
- Nodes 0, 1, and 2 do not have any ancestors.
- Node 3 has two ancestors 0 and 1.
- Node 4 has two ancestors 0 and 2.
- Node 5 has three ancestors 0, 1, and 3.
- Node 6 has five ancestors 0, 1, 2, 3, and 4.
- Node 7 has four ancestors 0, 1, 2, and 3.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/12/e2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, edgeList = [[0,1],[0,2],[0,3],[0,4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
<strong>Output:</strong> [[],[0],[0,1],[0,1,2],[0,1,2,3]]
<strong>Explanation:</strong>
The above diagram represents the input graph.
- Node 0 does not have any ancestor.
- Node 1 has one ancestor 0.
- Node 2 has two ancestors 0 and 1.
- Node 3 has three ancestors 0, 1, and 2.
- Node 4 has four ancestors 0, 1, 2, and 3.
</pre>



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



<ul><li><code>1 &lt;= n &lt;= 1000</code></li><li><code>0 &lt;= edges.length &lt;= min(2000, n * (n - 1) / 2)</code></li><li><code>edges[i].length == 2</code></li><li><code>0 &lt;= from<sub>i</sub>, to<sub>i</sub>&nbsp;&lt;= n - 1</code></li><li><code>from<sub>i</sub>&nbsp;!= to<sub>i</sub></code></li><li>There are no duplicate edges.</li><li>The graph is&nbsp;<strong>directed</strong>&nbsp;and&nbsp;<strong>acyclic</strong>.</li></ul>



<h2><strong>Solution: DFS</strong></h2>



<p>For each source node S, add it to all its reachable nodes by traversing the entire graph.<br>In one pass, only traverse each child node at most once.</p>



<p>Time complexity: O(VE)<br>Space complexity: (V+E)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; getAncestors(int n, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    vector&lt;vector&lt;int&gt;&gt; ans(n);
    vector&lt;vector&lt;int&gt;&gt; g(n);
    for (const auto&amp; e : edges)
      g[e[0]].push_back(e[1]);    
    
    function&lt;void(int, int)&gt; dfs = [&amp;](int s, int u) -&gt; void {
      for (int v : g[u]) {
        if (ans[v].empty() || ans[v].back() != s) {
          ans[v].push_back(s);
          dfs(s, v);
        }
      }
    };
    
    for (int i = 0; i &lt; n; ++i)
      dfs(i, i);  
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/">花花酱 LeetCode 2192. All Ancestors of a Node in a Directed Acyclic Graph</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/graph/leetcode-2192-all-ancestors-of-a-node-in-a-directed-acyclic-graph/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2003. Smallest Missing Genetic Value in Each Subtree</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Nov 2021 07:38:06 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8743</guid>

					<description><![CDATA[<p>There is a&#160;family tree&#160;rooted at&#160;0&#160;consisting of&#160;n&#160;nodes numbered&#160;0&#160;to&#160;n - 1. You are given a&#160;0-indexed&#160;integer array&#160;parents, where&#160;parents[i]&#160;is the parent for node&#160;i. Since node&#160;0&#160;is the&#160;root,&#160;parents[0] == -1. There&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/">花花酱 LeetCode 2003. Smallest Missing Genetic Value in Each Subtree</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>There is a&nbsp;<strong>family tree</strong>&nbsp;rooted at&nbsp;<code>0</code>&nbsp;consisting of&nbsp;<code>n</code>&nbsp;nodes numbered&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>. You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>parents</code>, where&nbsp;<code>parents[i]</code>&nbsp;is the parent for node&nbsp;<code>i</code>. Since node&nbsp;<code>0</code>&nbsp;is the&nbsp;<strong>root</strong>,&nbsp;<code>parents[0] == -1</code>.</p>



<p>There are&nbsp;<code>10<sup>5</sup></code>&nbsp;genetic values, each represented by an integer in the&nbsp;<strong>inclusive</strong>&nbsp;range&nbsp;<code>[1, 10<sup>5</sup>]</code>. You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, where&nbsp;<code>nums[i]</code>&nbsp;is a&nbsp;<strong>distinct&nbsp;</strong>genetic value for node&nbsp;<code>i</code>.</p>



<p>Return&nbsp;<em>an array&nbsp;</em><code>ans</code><em>&nbsp;of length&nbsp;</em><code>n</code><em>&nbsp;where&nbsp;</em><code>ans[i]</code><em>&nbsp;is</em>&nbsp;<em>the&nbsp;<strong>smallest</strong>&nbsp;genetic value that is&nbsp;<strong>missing</strong>&nbsp;from the subtree rooted at node</em>&nbsp;<code>i</code>.</p>



<p>The&nbsp;<strong>subtree</strong>&nbsp;rooted at a node&nbsp;<code>x</code>&nbsp;contains node&nbsp;<code>x</code>&nbsp;and all of its&nbsp;<strong>descendant</strong>&nbsp;nodes.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/08/23/case-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,0,0,2], nums = [1,2,3,4]
<strong>Output:</strong> [5,1,1,1]
<strong>Explanation:</strong> The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3] with values [1,2,3,4]. 5 is the smallest missing value.
- 1: The subtree contains only node 1 with value 2. 1 is the smallest missing value.
- 2: The subtree contains nodes [2,3] with values [3,4]. 1 is the smallest missing value.
- 3: The subtree contains only node 3 with value 4. 1 is the smallest missing value.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/08/23/case-2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,0,1,0,3,3], nums = [5,4,6,2,1,3]
<strong>Output:</strong> [7,1,1,4,2,1]
<strong>Explanation:</strong> The answer for each subtree is calculated as follows:
- 0: The subtree contains nodes [0,1,2,3,4,5] with values [5,4,6,2,1,3]. 7 is the smallest missing value.
- 1: The subtree contains nodes [1,2] with values [4,6]. 1 is the smallest missing value.
- 2: The subtree contains only node 2 with value 6. 1 is the smallest missing value.
- 3: The subtree contains nodes [3,4,5] with values [2,1,3]. 4 is the smallest missing value.
- 4: The subtree contains only node 4 with value 1. 2 is the smallest missing value.
- 5: The subtree contains only node 5 with value 3. 1 is the smallest missing value.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> parents = [-1,2,3,0,2,4,1], nums = [2,3,4,5,6,7,8]
<strong>Output:</strong> [1,1,1,1,1,1,1]
<strong>Explanation:</strong> The value 1 is missing from all the subtrees.
</pre>



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



<ul><li><code>n == parents.length == nums.length</code></li><li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= parents[i] &lt;= n - 1</code>&nbsp;for&nbsp;<code>i != 0</code></li><li><code>parents[0] == -1</code></li><li><code>parents</code>&nbsp;represents a valid tree.</li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li><li>Each&nbsp;<code>nums[i]</code>&nbsp;is distinct.</li></ul>



<h2><strong>Solution: DFS on a single path</strong></h2>



<p>One ancestors of node with value of 1 will have missing values greater than 1. We do a dfs on the path that from node with value 1 to the root.</p>



<p>Time complexity: O(n + max(nums))<br>Space complexity: O(n + max(nums)) </p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; smallestMissingValueSubtree(vector&lt;int&gt;&amp; parents, vector&lt;int&gt;&amp; nums) {
    const int n = parents.size();
    vector&lt;int&gt; ans(n, 1);
    vector&lt;int&gt; seen(100002);
    vector&lt;vector&lt;int&gt;&gt; g(n);
    for (int i = 1; i &lt; n; ++i)
      g[parents[i]].push_back(i);
    function&lt;void(int)&gt; dfs = [&amp;](int u) {
      if (seen[nums[u]]++) return;
      for (int v : g[u]) dfs(v);
    };
    int u = find(begin(nums), end(nums), 1) - begin(nums);
    for (int l = 1; u &lt; n &amp;&amp; u != -1; u = parents[u]) {
      dfs(u);
      while (seen[l]) ++l;
      ans[u] = l;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/">花花酱 LeetCode 2003. Smallest Missing Genetic Value in Each Subtree</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/tree/leetcode-2003-smallest-missing-genetic-value-in-each-subtree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2002. Maximum Product of the Length of Two Palindromic Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2002-maximum-product-of-the-length-of-two-palindromic-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2002-maximum-product-of-the-length-of-two-palindromic-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 20 Nov 2021 21:50:07 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8737</guid>

					<description><![CDATA[<p>Given a string&#160;s, find two&#160;disjoint palindromic subsequences&#160;of&#160;s&#160;such that the&#160;product&#160;of their lengths is&#160;maximized. The two subsequences are&#160;disjoint&#160;if they do not both pick a character at the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2002-maximum-product-of-the-length-of-two-palindromic-subsequences/">花花酱 LeetCode 2002. Maximum Product of the Length of Two Palindromic Subsequences</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>Given a string&nbsp;<code>s</code>, find two&nbsp;<strong>disjoint palindromic subsequences</strong>&nbsp;of&nbsp;<code>s</code>&nbsp;such that the&nbsp;<strong>product</strong>&nbsp;of their lengths is&nbsp;<strong>maximized</strong>. The two subsequences are&nbsp;<strong>disjoint</strong>&nbsp;if they do not both pick a character at the same index.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;possible&nbsp;<strong>product</strong>&nbsp;of the lengths of the two palindromic subsequences</em>.</p>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is&nbsp;<strong>palindromic</strong>&nbsp;if it reads the same forward and backward.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/08/24/two-palindromic-subsequences.png" alt="example-1"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcodecom"
<strong>Output:</strong> 9
<strong>Explanation</strong>: An optimal solution is to choose "ete" for the 1<sup>st</sup> subsequence and "cdc" for the 2<sup>nd</sup> subsequence.
The product of their lengths is: 3 * 3 = 9.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "bb"
<strong>Output:</strong> 1
<strong>Explanation</strong>: An optimal solution is to choose "b" (the first character) for the 1<sup>st</sup> subsequence and "b" (the second character) for the 2<sup>nd</sup> subsequence.
The product of their lengths is: 1 * 1 = 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "accbcaxxcxx"
<strong>Output:</strong> 25
<strong>Explanation</strong>: An optimal solution is to choose "accca" for the 1<sup>st</sup> subsequence and "xxcxx" for the 2<sup>nd</sup> subsequence.
The product of their lengths is: 5 * 5 = 25.
</pre>



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



<ul><li><code>2 &lt;= s.length &lt;= 12</code></li><li><code>s</code>&nbsp;consists of lowercase English letters only.</li></ul>



<h2><strong>Solution 1: DFS</strong></h2>



<p>Time complexity: O(3<sup>n</sup>*n)<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxProduct(string s) {    
    auto isPalindrom = [](const string&amp; s) {
      for (int i = 0; i &lt; s.length(); ++i)
        if (s[i] != s[s.size() - i - 1]) return false;
      return true;
    };
    const int n = s.size();
    vector&lt;string&gt; ss(3);
    size_t ans = 0;
    function&lt;void(int)&gt; dfs = [&amp;](int i) -&gt; void {
      if (i == n) {
        if (isPalindrom(ss[0]) &amp;&amp; isPalindrom(ss[1]))
          ans = max(ans, ss[0].size() * ss[1].size());
        return;
      }
      for (int k = 0; k &lt; 3; ++k) {
        ss[k].push_back(s[i]);
        dfs(i + 1); 
        ss[k].pop_back();  
      }      
    };
    dfs(0);
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution: Subsets + Bitmask + All Pairs</strong></h2>



<p>Time complexity: O(2<sup>2n</sup>)<br>Space complexity: O(2<sup>n</sup>)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxProduct(string s) {    
    auto isPalindrom = [](const string&amp; s) {
      for (int i = 0; i &lt; s.length(); ++i)
        if (s[i] != s[s.size() - i - 1]) return false;
      return true;
    };
    const int n = s.size();
    unordered_set&lt;int&gt; p;
    for (int i = 0; i &lt; (1 &lt;&lt; n); ++i) {
      string t;
      for (int j = 0; j &lt; n; ++j)
        if (i &gt;&gt; j &amp; 1) t.push_back(s[j]);
      if (isPalindrom(t))
        p.insert(i);
    }
    int ans = 0;
    for (int s1 : p)
      for (int s2 : p) 
        if (!(s1 &amp; s2))
          ans = max(ans, __builtin_popcount(s1) * __builtin_popcount(s2));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2002-maximum-product-of-the-length-of-two-palindromic-subsequences/">花花酱 LeetCode 2002. Maximum Product of the Length of Two Palindromic Subsequences</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/searching/leetcode-2002-maximum-product-of-the-length-of-two-palindromic-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2065. Maximum Path Quality of a Graph</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2065-maximum-path-quality-of-a-graph/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2065-maximum-path-quality-of-a-graph/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 07 Nov 2021 22:09:43 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8685</guid>

					<description><![CDATA[<p>There is an&#160;undirected&#160;graph with&#160;n&#160;nodes numbered from&#160;0&#160;to&#160;n - 1&#160;(inclusive). You are given a&#160;0-indexed&#160;integer array&#160;values&#160;where&#160;values[i]&#160;is the&#160;value&#160;of the&#160;ith&#160;node. You are also given a&#160;0-indexed&#160;2D integer array&#160;edges, where each&#160;edges[j] =&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2065-maximum-path-quality-of-a-graph/">花花酱 LeetCode 2065. Maximum Path Quality of a Graph</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>There is an&nbsp;<strong>undirected</strong>&nbsp;graph with&nbsp;<code>n</code>&nbsp;nodes numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;(<strong>inclusive</strong>). You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>values</code>&nbsp;where&nbsp;<code>values[i]</code>&nbsp;is the&nbsp;<strong>value&nbsp;</strong>of the&nbsp;<code>i<sup>th</sup></code>&nbsp;node. You are also given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array&nbsp;<code>edges</code>, where each&nbsp;<code>edges[j] = [u<sub>j</sub>, v<sub>j</sub>, time<sub>j</sub>]</code>&nbsp;indicates that there is an undirected edge between the nodes&nbsp;<code>u<sub>j</sub></code>&nbsp;and&nbsp;<code>v<sub>j</sub></code>,and it takes&nbsp;<code>time<sub>j</sub></code>&nbsp;seconds to travel between the two nodes. Finally, you are given an integer&nbsp;<code>maxTime</code>.</p>



<p>A&nbsp;<strong>valid</strong>&nbsp;<strong>path</strong>&nbsp;in the graph is any path that starts at node&nbsp;<code>0</code>, ends at node&nbsp;<code>0</code>, and takes&nbsp;<strong>at most</strong>&nbsp;<code>maxTime</code>&nbsp;seconds to complete. You may visit the same node multiple times. The&nbsp;<strong>quality</strong>&nbsp;of a valid path is the&nbsp;<strong>sum</strong>&nbsp;of the values of the&nbsp;<strong>unique nodes</strong>&nbsp;visited in the path (each node&#8217;s value is added&nbsp;<strong>at most once</strong>&nbsp;to the sum).</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;quality of a valid path</em>.</p>



<p><strong>Note:</strong>&nbsp;There are&nbsp;<strong>at most four</strong>&nbsp;edges connected to each node.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/19/ex1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> values = [0,32,10,43], edges = [[0,1,10],[1,2,15],[0,3,10]], maxTime = 49
<strong>Output:</strong> 75
<strong>Explanation:</strong>
One possible path is 0 -&gt; 1 -&gt; 0 -&gt; 3 -&gt; 0. The total time taken is 10 + 10 + 10 + 10 = 40 &lt;= 49.
The nodes visited are 0, 1, and 3, giving a maximal path quality of 0 + 32 + 43 = 75.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/19/ex2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> values = [5,10,15,20], edges = [[0,1,10],[1,2,10],[0,3,10]], maxTime = 30
<strong>Output:</strong> 25
<strong>Explanation:</strong>
One possible path is 0 -&gt; 3 -&gt; 0. The total time taken is 10 + 10 = 20 &lt;= 30.
The nodes visited are 0 and 3, giving a maximal path quality of 5 + 20 = 25.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/19/ex31drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> values = [1,2,3,4], edges = [[0,1,10],[1,2,11],[2,3,12],[1,3,13]], maxTime = 50
<strong>Output:</strong> 7
<strong>Explanation:</strong>
One possible path is 0 -&gt; 1 -&gt; 3 -&gt; 1 -&gt; 0. The total time taken is 10 + 13 + 13 + 10 = 46 &lt;= 50.
The nodes visited are 0, 1, and 3, giving a maximal path quality of 1 + 2 + 4 = 7.</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/21/ex4drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> values = [0,1,2], edges = [[1,2,10]], maxTime = 10
<strong>Output:</strong> 0
<strong>Explanation:</strong> 
The only path is 0. The total time taken is 0.
The only node visited is 0, giving a maximal path quality of 0.
</pre>



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



<ul><li><code>n == values.length</code></li><li><code>1 &lt;= n &lt;= 1000</code></li><li><code>0 &lt;= values[i] &lt;= 10<sup>8</sup></code></li><li><code>0 &lt;= edges.length &lt;= 2000</code></li><li><code>edges[j].length == 3</code></li><li><code>0 &lt;= u<sub>j&nbsp;</sub>&lt; v<sub>j</sub>&nbsp;&lt;= n - 1</code></li><li><code>10 &lt;= time<sub>j</sub>, maxTime &lt;= 100</code></li><li>All the pairs&nbsp;<code>[u<sub>j</sub>, v<sub>j</sub>]</code>&nbsp;are&nbsp;<strong>unique</strong>.</li><li>There are&nbsp;<strong>at most four</strong>&nbsp;edges connected to each node.</li><li>The graph may not be connected.</li></ul>



<h2><strong>Solution: DFS</strong></h2>



<p>Given time &gt;= 10 and maxTime &lt;= 100, the path length is at most 10, given at most four edges connected to each node.<br>Time complexity: O(4<sup>10</sup>)<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maximalPathQuality(vector&lt;int&gt;&amp; values, vector&lt;vector&lt;int&gt;&gt;&amp; edges, int maxTime) {
    const int n = values.size();
    vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; g(n);
    for (const auto&amp; e : edges) {
      g[e[0]].emplace_back(e[1], e[2]);
      g[e[1]].emplace_back(e[0], e[2]);
    }
    vector&lt;int&gt; seen(n);
    int ans = 0;
    function&lt;void(int, int, int)&gt; dfs = [&amp;](int u, int t, int s) {
      if (++seen[u] == 1) s += values[u];
      if (u == 0) ans = max(ans, s);
      for (auto [v, d] : g[u])
        if (t + d &lt;= maxTime) dfs(v, t + d, s);
      if (--seen[u] == 0) s -= values[u];
    };
    dfs(0, 0, 0);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2065-maximum-path-quality-of-a-graph/">花花酱 LeetCode 2065. Maximum Path Quality of a Graph</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/searching/leetcode-2065-maximum-path-quality-of-a-graph/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1905. Count Sub Islands</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-1905-count-sub-islands/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-1905-count-sub-islands/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Aug 2021 22:42:04 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[cc]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[island]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8587</guid>

					<description><![CDATA[<p>You are given two&#160;m x n&#160;binary matrices&#160;grid1&#160;and&#160;grid2&#160;containing only&#160;0&#8216;s (representing water) and&#160;1&#8216;s (representing land). An&#160;island&#160;is a group of&#160;1&#8216;s connected&#160;4-directionally&#160;(horizontal or vertical). Any cells outside of the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1905-count-sub-islands/">花花酱 LeetCode 1905. Count Sub Islands</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>You are given two&nbsp;<code>m x n</code>&nbsp;binary matrices&nbsp;<code>grid1</code>&nbsp;and&nbsp;<code>grid2</code>&nbsp;containing only&nbsp;<code>0</code>&#8216;s (representing water) and&nbsp;<code>1</code>&#8216;s (representing land). An&nbsp;<strong>island</strong>&nbsp;is a group of&nbsp;<code>1</code>&#8216;s connected&nbsp;<strong>4-directionally</strong>&nbsp;(horizontal or vertical). Any cells outside of the grid are considered water cells.</p>



<p>An island in&nbsp;<code>grid2</code>&nbsp;is considered a&nbsp;<strong>sub-island&nbsp;</strong>if there is an island in&nbsp;<code>grid1</code>&nbsp;that contains&nbsp;<strong>all</strong>&nbsp;the cells that make up&nbsp;<strong>this</strong>&nbsp;island in&nbsp;<code>grid2</code>.</p>



<p>Return the&nbsp;<em><strong>number</strong>&nbsp;of islands in&nbsp;</em><code>grid2</code>&nbsp;<em>that are considered&nbsp;<strong>sub-islands</strong></em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/06/10/test1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
<strong>Output:</strong> 3
<strong>Explanation: </strong>In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
<strong>Output:</strong> 2 
<strong>Explanation: </strong>In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
</pre>



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



<ul><li><code>m == grid1.length == grid2.length</code></li><li><code>n == grid1[i].length == grid2[i].length</code></li><li><code>1 &lt;= m, n &lt;= 500</code></li><li><code>grid1[i][j]</code>&nbsp;and&nbsp;<code>grid2[i][j]</code>&nbsp;are either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution: Coloring</strong></h2>



<p>Give each island in grid1 a different color. Whiling using the same method to find island and coloring it in grid2, we also check whether the same cell in grid1 always has the same color.</p>



<p>Time complexity: O(mn)<br>Space complexity: O(1) modify in place or O(mn)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countSubIslands(vector&lt;vector&lt;int&gt;&gt;&amp; grid1, vector&lt;vector&lt;int&gt;&gt;&amp; grid2) {
    const int m = grid1.size();
    const int n = grid1[0].size();
    int valid = 1;
    
    function&lt;void(int, int, int, int)&gt; color = [&amp;](int i, int j, int c, int p) {
      if (i &lt; 0 || i &gt;= m || j &lt; 0 || j &gt;= n) return;
      auto&amp; gc = p ? grid2 : grid1;
      auto&amp; go = p ? grid1 : grid2;
      if (gc[i][j] != 1) return;
      gc[i][j] = c;
      if (p &amp;&amp; go[i][j] != c) valid = 0;
      color(i + 1, j, c, p);
      color(i - 1, j, c, p);
      color(i, j + 1, c, p);
      color(i, j - 1, c, p);
    };
        
    for (int i = 0, c = 2; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        if (grid1[i][j] == 1) color(i, j, c++, 0);
    
    int ans = 0;
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j)
        if (grid2[i][j] == 1 &amp;&amp; grid1[i][j]) {
          valid = 1;
          color(i, j, grid1[i][j], 1);
          ans += valid;
        }    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/graph/leetcode-1905-count-sub-islands/">花花酱 LeetCode 1905. Count Sub Islands</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/graph/leetcode-1905-count-sub-islands/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1849. Splitting a String Into Descending Consecutive Values</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1849-splitting-a-string-into-descending-consecutive-values/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1849-splitting-a-string-into-descending-consecutive-values/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 03 May 2021 06:25:54 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8431</guid>

					<description><![CDATA[<p>You are given a string&#160;s&#160;that consists of only digits. Check if we can split&#160;s&#160;into&#160;two or more non-empty substrings&#160;such that the&#160;numerical values&#160;of the substrings are in&#160;descending&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1849-splitting-a-string-into-descending-consecutive-values/">花花酱 LeetCode 1849. Splitting a String Into Descending Consecutive Values</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>You are given a string&nbsp;<code>s</code>&nbsp;that consists of only digits.</p>



<p>Check if we can split&nbsp;<code>s</code>&nbsp;into&nbsp;<strong>two or more non-empty substrings</strong>&nbsp;such that the&nbsp;<strong>numerical values</strong>&nbsp;of the substrings are in&nbsp;<strong>descending order</strong>&nbsp;and the&nbsp;<strong>difference</strong>&nbsp;between numerical values of every two&nbsp;<strong>adjacent</strong>&nbsp;<strong>substrings</strong>&nbsp;is equal to&nbsp;<code>1</code>.</p>



<ul><li>For example, the string&nbsp;<code>s = "0090089"</code>&nbsp;can be split into&nbsp;<code>["0090", "089"]</code>&nbsp;with numerical values&nbsp;<code>[90,89]</code>. The values are in descending order and adjacent values differ by&nbsp;<code>1</code>, so this way is valid.</li><li>Another example, the string&nbsp;<code>s = "001"</code>&nbsp;can be split into&nbsp;<code>["0", "01"]</code>,&nbsp;<code>["00", "1"]</code>, or&nbsp;<code>["0", "0", "1"]</code>. However all the ways are invalid because they have numerical values&nbsp;<code>[0,1]</code>,&nbsp;<code>[0,1]</code>, and&nbsp;<code>[0,0,1]</code>&nbsp;respectively, all of which are not in descending order.</li></ul>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if it is possible to split</em>&nbsp;<code>s</code>​​​​​​&nbsp;<em>as described above</em><em>, or&nbsp;</em><code>false</code><em>&nbsp;otherwise.</em></p>



<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous sequence of characters in a string.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1234"
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no valid way to split s.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "050043"
<strong>Output:</strong> true
<strong>Explanation:</strong> s can be split into ["05", "004", "3"] with numerical values [5,4,3].
The values are in descending order with adjacent values differing by 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "9080701"
<strong>Output:</strong> false
<strong>Explanation:</strong> There is no valid way to split s.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "10009998"
<strong>Output:</strong> true
<strong>Explanation:</strong> s can be split into ["100", "099", "98"] with numerical values [100,99,98].
The values are in descending order with adjacent values differing by 1.
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 20</code></li><li><code>s</code>&nbsp;only consists of digits.</li></ul>



<h2><strong>Solution: DFS</strong></h2>



<p>Time complexity: O(2<sup>n</sup>)<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  bool splitString(string s) {
    const int n = s.length();
    vector&lt;long&gt; nums;
    function&lt;bool(int)&gt; dfs = [&amp;](int p) {
      if (p == n) return nums.size() &gt;= 2;
      long cur = 0;
      for (int i = p; i &lt; n &amp;&amp; cur &lt; 1e11; ++i) {        
        cur = cur * 10 + (s[i] - '0');
        if (nums.empty() || cur + 1 == nums.back()) {
          nums.push_back(cur);
          if (dfs(i + 1)) return true;
          nums.pop_back();
        }
        if (!nums.empty() &amp;&amp; cur &gt;= nums.back()) break;                
      }
      return false;
    };
    return dfs(0);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1849-splitting-a-string-into-descending-consecutive-values/">花花酱 LeetCode 1849. Splitting a String Into Descending Consecutive Values</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/searching/leetcode-1849-splitting-a-string-into-descending-consecutive-values/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1815. Maximum Number of Groups Getting Fresh Donuts</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1815-maximum-number-of-groups-getting-fresh-donuts/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1815-maximum-number-of-groups-getting-fresh-donuts/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 05 Apr 2021 07:34:44 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[permutation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8306</guid>

					<description><![CDATA[<p>There is a donuts shop that bakes donuts in batches of&#160;batchSize. They have a rule where they must serve&#160;all&#160;of the donuts of a batch before&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1815-maximum-number-of-groups-getting-fresh-donuts/">花花酱 LeetCode 1815. Maximum Number of Groups Getting Fresh Donuts</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 is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1815. Maximum Number of Groups Getting Fresh Donuts - 刷题找工作 EP391" width="500" height="281" src="https://www.youtube.com/embed/ZpFno2IEHWE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>There is a donuts shop that bakes donuts in batches of&nbsp;<code>batchSize</code>. They have a rule where they must serve&nbsp;<strong>all</strong>&nbsp;of the donuts of a batch before serving any donuts of the next batch. You are given an integer&nbsp;<code>batchSize</code>&nbsp;and an integer array&nbsp;<code>groups</code>, where&nbsp;<code>groups[i]</code>&nbsp;denotes that there is a group of&nbsp;<code>groups[i]</code>&nbsp;customers that will visit the shop. Each customer will get exactly one donut.</p>



<p>When a group visits the shop, all customers of the group must be served before serving any of the following groups. A group will be happy if they all get fresh donuts. That is, the first customer of the group does not receive a donut that was left over from the previous group.</p>



<p>You can freely rearrange the ordering of the groups. Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;possible number of happy groups after rearranging the groups.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> batchSize = 3, groups = [1,2,3,4,5,6]
<strong>Output:</strong> 4
<strong>Explanation:</strong> You can arrange the groups as [6,2,4,5,1,3]. Then the 1<sup>st</sup>, 2<sup>nd</sup>, 4<sup>th</sup>, and 6<sup>th</sup> groups will be happy.
</pre>



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



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



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



<ul><li><code>1 &lt;= batchSize &lt;= 9</code></li><li><code>1 &lt;= groups.length &lt;= 30</code></li><li><code>1 &lt;= groups[i] &lt;= 10<sup>9</sup></code></li></ul>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-1.png" alt="" class="wp-image-8314" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<h2><strong>Solution 0: Binary Mask DP</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-2.png" alt="" class="wp-image-8315" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Time complexity: O(n*2<sup>n</sup>) TLE<br>Space complexity: O(2<sup>n</sup>)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, TLE, 42/67 Passed
class Solution {
public:
  int maxHappyGroups(int b, vector&lt;int&gt;&amp; groups) {
    const int n = groups.size();
    vector&lt;int&gt; dp(1 &lt;&lt; n);
    for (int mask = 0; mask &lt; 1 &lt;&lt; n; ++mask) {
      int s = 0;
      for (int i = 0; i &lt; n; ++i)
        if (mask &amp; (1 &lt;&lt; i)) s = (s + groups[i]) % b;
      for (int i = 0; i &lt; n; ++i)
        if (!(mask &amp; (1 &lt;&lt; i)))
          dp[mask | (1 &lt;&lt; i)] = max(dp[mask | (1 &lt;&lt; i)],
                                    dp[mask] + (s == 0));
    }
    return dp[(1 &lt;&lt; n) - 1];
  }
};</pre>
</div></div>



<h2><strong>Solution 1: Recursion w/ Memoization</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-3.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-3.png" alt="" class="wp-image-8316" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1815-ep391-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>State: count of group size % batchSize</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 888 ms, 61.9 MB
class Solution {
public:
  int maxHappyGroups(int b, vector&lt;int&gt;&amp; groups) {
    int ans = 0;
    vector&lt;int&gt; count(b);
    for (int g : groups) ++count[g % b];      
    map&lt;vector&lt;int&gt;, int&gt; cache;
    function&lt;int(int)&gt; dp = [&amp;](int s) {
      auto it = cache.find(count);
      if (it != cache.end()) return it-&gt;second;
      int ans = 0;
      for (int i = 1; i &lt; b; ++i) {
        if (!count[i]) continue;
        --count[i];
        ans = max(ans, (s == 0) + dp((s + i) % b));
        ++count[i];
      }
      return cache[count] = ans;
    };    
    return count[0] + dp(0);
  }
};</pre>

</div><h2 class="tabtitle">C++/Hashtable</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua 380 ms, 59.2 MB
struct VectorHasher {
  size_t operator()(const vector&lt;int&gt;&amp; V) const {
    size_t hash = V.size();
    for (auto i : V)
      hash ^= i + 0x9e3779b9 + (hash &lt;&lt; 6) + (hash &gt;&gt; 2);
    return hash;
  }
};
class Solution {
public:
  int maxHappyGroups(int b, vector&lt;int&gt;&amp; groups) {
    int ans = 0;
    vector&lt;int&gt; count(b);
    for (int g : groups) ++count[g % b];      
    unordered_map&lt;vector&lt;int&gt;, int, VectorHasher&gt; cache;
    function&lt;int(int)&gt; dp = [&amp;](int s) {
      auto it = cache.find(count);
      if (it != cache.end()) return it-&gt;second;
      int ans = 0;
      for (int i = 1; i &lt; b; ++i) {
        if (!count[i]) continue;
        --count[i];
        ans = max(ans, (s == 0) + dp((s + b - i) % b));
        ++count[i];
      }
      return cache[count] = ans;
    };    
    return count[0] + dp(0);
  }
};</pre>

</div><h2 class="tabtitle">C++/OPT</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 0 ms, 8.1 MB
class Solution {
public:
  int maxHappyGroups(int b, vector&lt;int&gt;&amp; groups) {
    int ans = 0;
    vector&lt;int&gt; count(b);
    for (int g : groups) {
      const int r = g % b;
      if (r == 0) { ++ans; continue; }      
      if (count[b - r]) {
        --count[b - r];
        ++ans;
      } else {
        ++count[r];
      }
    }    
    map&lt;vector&lt;int&gt;, int&gt; cache;
    function&lt;int(int, int)&gt; dp = [&amp;](int r, int n) {
      if (n == 0) return 0;
      auto it = cache.find(count);
      if (it != cache.end()) return it-&gt;second;
      int ans = 0;
      for (int i = 1; i &lt; b; ++i) {
        if (!count[i]) continue;
        --count[i];
        ans = max(ans, (r == 0) + dp((r + b - i) % b, n - 1));
        ++count[i];
      }
      return cache[count] = ans;
    };
    const int n = accumulate(begin(count), end(count), 0);
    return ans + (n ? dp(0, n) : 0);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1815-maximum-number-of-groups-getting-fresh-donuts/">花花酱 LeetCode 1815. Maximum Number of Groups Getting Fresh Donuts</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/dynamic-programming/leetcode-1815-maximum-number-of-groups-getting-fresh-donuts/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1774. Closest Dessert Cost</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1774-closest-dessert-cost/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1774-closest-dessert-cost/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Feb 2021 04:48:52 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8164</guid>

					<description><![CDATA[<p>You would like to make dessert and are preparing to buy the ingredients. You have&#160;n&#160;ice cream base flavors and&#160;m&#160;types of toppings to choose from. You&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1774-closest-dessert-cost/">花花酱 LeetCode 1774. Closest Dessert Cost</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>You would like to make dessert and are preparing to buy the ingredients. You have&nbsp;<code>n</code>&nbsp;ice cream base flavors and&nbsp;<code>m</code>&nbsp;types of toppings to choose from. You must follow these rules when making your dessert:</p>



<ul><li>There must be&nbsp;<strong>exactly one</strong>&nbsp;ice cream base.</li><li>You can add&nbsp;<strong>one or more</strong>&nbsp;types of topping or have no toppings at all.</li><li>There are&nbsp;<strong>at most two</strong>&nbsp;of&nbsp;<strong>each type</strong>&nbsp;of topping.</li></ul>



<p>You are given three inputs:</p>



<ul><li><code>baseCosts</code>, an integer array of length&nbsp;<code>n</code>, where each&nbsp;<code>baseCosts[i]</code>&nbsp;represents the price of the&nbsp;<code>i<sup>th</sup></code>&nbsp;ice cream base flavor.</li><li><code>toppingCosts</code>, an integer array of length&nbsp;<code>m</code>, where each&nbsp;<code>toppingCosts[i]</code>&nbsp;is the price of&nbsp;<strong>one</strong>&nbsp;of the&nbsp;<code>i<sup>th</sup></code>&nbsp;topping.</li><li><code>target</code>, an integer representing your target price for dessert.</li></ul>



<p>You want to make a dessert with a total cost as close to&nbsp;<code>target</code>&nbsp;as possible.</p>



<p>Return&nbsp;<em>the closest possible cost of the dessert to&nbsp;</em><code>target</code>. If there are multiple, return&nbsp;<em>the&nbsp;<strong>lower</strong>&nbsp;one.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> baseCosts = [1,7], toppingCosts = [3,4], target = 10
<strong>Output:</strong> 10
<strong>Explanation:</strong> Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> baseCosts = [2,3], toppingCosts = [4,5,100], target = 18
<strong>Output:</strong> 17
<strong>Explanation:</strong> Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> baseCosts = [3,10], toppingCosts = [2,5], target = 9
<strong>Output:</strong> 8
<strong>Explanation:</strong> It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> baseCosts = [10], toppingCosts = [1], target = 1
<strong>Output:</strong> 10
<strong>Explanation:</strong> Notice that you don't have to have any toppings, but you must have exactly one base.</pre>



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



<ul><li><code>n == baseCosts.length</code></li><li><code>m == toppingCosts.length</code></li><li><code>1 &lt;= n, m &lt;= 10</code></li><li><code>1 &lt;= baseCosts[i], toppingCosts[i] &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= target &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: DP</strong> / <strong>Knapsack</strong> </h2>



<p>Pre-compute the costs of all possible combinations of toppings.</p>



<p>Time complexity: O(sum(toppings) * 2 * (m + n)) ~ O(10^6)<br>Space  complexity: O(sum(toppings)) ~ O(10^5)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int closestCost(vector&lt;int&gt;&amp; bs, vector&lt;int&gt;&amp; ts, int target) {
    const int kMax = 2 * accumulate(begin(ts), end(ts), 0);
    int min_diff = INT_MAX;
    int ans = INT_MAX;
    vector&lt;int&gt; dp(kMax + 1);
    dp[0] = 1;
    for (int t : ts) {
      for (int i = kMax; i &gt;= 0; --i) {
        if (!dp[i]) continue;
        if (i + t &lt;= kMax) dp[i + t] = 1;
        if (i + 2 * t &lt;= kMax) dp[i + 2 * t] = 1;        
      }
    }   
    for (int i = 0; i &lt;= kMax; ++i) {
      if (!dp[i]) continue;
       for (int b : bs) {
        const int diff = abs(b + i - target);
        if (diff &lt; min_diff || diff == min_diff &amp;&amp; b + i &lt; ans) {
          min_diff = diff;
          ans = b + i;
        }
      }
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: DFS</strong></h2>



<p>Combination</p>



<p>Time complexity: O(3^m * n)<br>Space complexity: O(m)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int closestCost(vector&lt;int&gt;&amp; bs, vector&lt;int&gt;&amp; ts, int target) {
    const int m = ts.size();
    int min_diff = INT_MAX;
    int ans = INT_MAX;
    function&lt;void(int, int)&gt; dfs = [&amp;](int s, int cur) {
      if (s == m) {
        for (int b : bs) {
          const int total = b + cur;
          const int diff = abs(total - target);
          if (diff &lt; min_diff 
              || diff == min_diff &amp;&amp; total &lt; ans) {
            min_diff = diff;
            ans = total;
          }
        }
        return;
      }      
      for (int i = s; i &lt; m; ++i) {
        dfs(i + 1, cur);
        dfs(i + 1, cur + ts[i]);
        dfs(i + 1, cur + ts[i] * 2);
      }
    };    
    dfs(0, 0);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1774-closest-dessert-cost/">花花酱 LeetCode 1774. Closest Dessert Cost</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/dynamic-programming/leetcode-1774-closest-dessert-cost/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1766. Tree of Coprimes</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1766-tree-of-coprimes/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1766-tree-of-coprimes/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Feb 2021 06:16:18 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[ancestor]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8139</guid>

					<description><![CDATA[<p>There is a tree (i.e.,&#160;a connected, undirected graph that has no cycles) consisting of&#160;n&#160;nodes numbered from&#160;0&#160;to&#160;n - 1&#160;and exactly&#160;n - 1&#160;edges. Each node has a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1766-tree-of-coprimes/">花花酱 LeetCode 1766. Tree of Coprimes</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>There is a tree (i.e.,&nbsp;a connected, undirected graph that has no cycles) consisting of&nbsp;<code>n</code>&nbsp;nodes numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;and exactly&nbsp;<code>n - 1</code>&nbsp;edges. Each node has a value associated with it, and the&nbsp;<strong>root</strong>&nbsp;of the tree is node&nbsp;<code>0</code>.</p>



<p>To represent this tree, you are given an integer array&nbsp;<code>nums</code>&nbsp;and a 2D array&nbsp;<code>edges</code>. Each&nbsp;<code>nums[i]</code>&nbsp;represents the&nbsp;<code>i<sup>th</sup></code>&nbsp;node&#8217;s value, and each&nbsp;<code>edges[j] = [u<sub>j</sub>, v<sub>j</sub>]</code>&nbsp;represents an edge between nodes&nbsp;<code>u<sub>j</sub></code>&nbsp;and&nbsp;<code>v<sub>j</sub></code>&nbsp;in the tree.</p>



<p>Two values&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>&nbsp;are&nbsp;<strong>coprime</strong>&nbsp;if&nbsp;<code>gcd(x, y) == 1</code>&nbsp;where&nbsp;<code>gcd(x, y)</code>&nbsp;is the&nbsp;<strong>greatest common divisor</strong>&nbsp;of&nbsp;<code>x</code>&nbsp;and&nbsp;<code>y</code>.</p>



<p>An ancestor of a node&nbsp;<code>i</code>&nbsp;is any other node on the shortest path from node&nbsp;<code>i</code>&nbsp;to the&nbsp;<strong>root</strong>. A node is&nbsp;<strong>not&nbsp;</strong>considered an ancestor of itself.</p>



<p>Return&nbsp;<em>an array&nbsp;</em><code>ans</code><em>&nbsp;of size&nbsp;</em><code>n</code>,&nbsp;<em>where&nbsp;</em><code>ans[i]</code><em>&nbsp;is the closest ancestor to node&nbsp;</em><code>i</code><em>&nbsp;such that&nbsp;</em><code>nums[i]</code>&nbsp;<em>and&nbsp;</em><code>nums[ans[i]]</code>&nbsp;are&nbsp;<strong>coprime</strong>, or&nbsp;<code>-1</code><em>&nbsp;if there is no such ancestor</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,3,2], edges = [[0,1],[1,2],[1,3]]
<strong>Output:</strong> [-1,0,0,1]
<strong>Explanation:</strong> In the above figure, each node's value is in parentheses.
- Node 0 has no coprime ancestors.
- Node 1 has only one ancestor, node 0. Their values are coprime (gcd(2,3) == 1).
- Node 2 has two ancestors, nodes 1 and 0. Node 1's value is not coprime (gcd(3,3) == 3), but node 0's
  value is (gcd(2,3) == 1), so node 0 is the closest valid ancestor.
- Node 3 has two ancestors, nodes 1 and 0. It is coprime with node 1 (gcd(3,2) == 1), so node 1 is its
  closest valid ancestor.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/01/06/untitled-diagram1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,6,10,2,3,6,15], edges = [[0,1],[0,2],[1,3],[1,4],[2,5],[2,6]]
<strong>Output:</strong> [-1,0,-1,0,0,0,-1]
</pre>



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



<ul><li><code>nums.length == n</code></li><li><code>1 &lt;= nums[i] &lt;= 50</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>edges.length == n - 1</code></li><li><code>edges[j].length == 2</code></li><li><code>0 &lt;= u<sub>j</sub>, v<sub>j</sub>&nbsp;&lt; n</code></li><li><code>u<sub>j</sub>&nbsp;!= v<sub>j</sub></code></li></ul>



<h2><strong>Solution: DFS + Stack</strong></h2>



<p>Pre-compute for coprimes for each number.</p>



<p>For each node, enumerate all it&#8217;s coprime numbers, find the deepest occurrence. </p>



<p>Time complexity: O(n * max(nums))<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; getCoprimes(vector&lt;int&gt;&amp; nums, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    constexpr int kMax = 50;
    const int n = nums.size();
    vector&lt;vector&lt;int&gt;&gt; g(n);
    for (const auto&amp; e : edges) {
      g[e[0]].push_back(e[1]);
      g[e[1]].push_back(e[0]);
    }    
        
    vector&lt;vector&lt;int&gt;&gt; coprime(kMax + 1);
    for (int i = 1; i &lt;= kMax; ++i)
      for (int j = 1; j &lt;= kMax; ++j)
        if (gcd(i, j) == 1) coprime[i].push_back(j);
    
    vector&lt;int&gt; ans(n, INT_MAX);
    vector&lt;vector&lt;pair&lt;int, int&gt;&gt;&gt; p(kMax + 1);
    function&lt;void(int, int)&gt; dfs = [&amp;](int cur, int d) {    
      int max_d = -1;
      int ancestor = -1;
      for (int co : coprime[nums[cur]])
        if (!p[co].empty() &amp;&amp; p[co].back().first &gt; max_d) {
          max_d = p[co].back().first;
          ancestor = p[co].back().second;          
        }
      ans[cur] = ancestor;
      p[nums[cur]].emplace_back(d, cur);
      for (int nxt : g[cur])
        if (ans[nxt] == INT_MAX) dfs(nxt, d + 1);
      p[nums[cur]].pop_back();
    };
    
    dfs(0, 0);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1766-tree-of-coprimes/">花花酱 LeetCode 1766. Tree of Coprimes</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/searching/leetcode-1766-tree-of-coprimes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1718. Construct the Lexicographically Largest Valid Sequence</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1718-construct-the-lexicographically-largest-valid-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1718-construct-the-lexicographically-largest-valid-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Jan 2021 04:02:45 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7950</guid>

					<description><![CDATA[<p>Given an integer&#160;n, find a sequence that satisfies all of the following: The integer&#160;1&#160;occurs once in the sequence. Each integer between&#160;2&#160;and&#160;n&#160;occurs twice in the sequence.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1718-construct-the-lexicographically-largest-valid-sequence/">花花酱 LeetCode 1718. Construct the Lexicographically Largest Valid Sequence</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>Given an integer&nbsp;<code>n</code>, find a sequence that satisfies all of the following:</p>



<ul><li>The integer&nbsp;<code>1</code>&nbsp;occurs once in the sequence.</li><li>Each integer between&nbsp;<code>2</code>&nbsp;and&nbsp;<code>n</code>&nbsp;occurs twice in the sequence.</li><li>For every integer&nbsp;<code>i</code>&nbsp;between&nbsp;<code>2</code>&nbsp;and&nbsp;<code>n</code>, the&nbsp;<strong>distance</strong>&nbsp;between the two occurrences of&nbsp;<code>i</code>&nbsp;is exactly&nbsp;<code>i</code>.</li></ul>



<p>The&nbsp;<strong>distance</strong>&nbsp;between two numbers on the sequence,&nbsp;<code>a[i]</code>&nbsp;and&nbsp;<code>a[j]</code>, is the absolute difference of their indices,&nbsp;<code>|j - i|</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>lexicographically largest</strong>&nbsp;sequence</em><em>. It is guaranteed that under the given constraints, there is always a solution.</em></p>



<p>A sequence&nbsp;<code>a</code>&nbsp;is lexicographically larger than a sequence&nbsp;<code>b</code>&nbsp;(of the same length) if in the first position where&nbsp;<code>a</code>&nbsp;and&nbsp;<code>b</code>&nbsp;differ, sequence&nbsp;<code>a</code>&nbsp;has a number greater than the corresponding number in&nbsp;<code>b</code>. For example,&nbsp;<code>[0,1,9,0]</code>&nbsp;is lexicographically larger than&nbsp;<code>[0,1,5,6]</code>&nbsp;because the first position they differ is at the third number, and&nbsp;<code>9</code>&nbsp;is greater than&nbsp;<code>5</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3
<strong>Output:</strong> [3,1,2,3,2]
<strong>Explanation:</strong> [2,3,2,1,3] is also a valid sequence, but [3,1,2,3,2] is the lexicographically largest valid sequence.
</pre>



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



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



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



<ul><li><code>1 &lt;= n &lt;= 20</code></li></ul>



<h2><strong>Solution: Search</strong></h2>



<p>Search from left to right, largest to smallest.</p>



<p>Time complexity: O(n!)?<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; constructDistancedSequence(int n) {
    const int len = 2 * n - 1;
    vector&lt;int&gt; ans(len);    
    function&lt;bool(int, int)&gt; dfs = [&amp;](int i, int s) {      
      if (i == len) return true;
      if (ans[i]) return dfs(i + 1, s);
      for (int d = n; d &gt; 0; --d) {
        const int j = i + (d == 1 ? 0 : d);
        if ((s &amp; (1 &lt;&lt; d)) || j &gt;= len || ans[j]) continue;
        ans[i] = ans[j] = d;
        if (dfs(i + 1, s | (1 &lt;&lt; d))) return true;
        ans[i] = ans[j] = 0;
      }
      return false;
    };
    dfs(0, 0);
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  private boolean dfs(int[] ans, int n, int i, int s) {
    if (i == ans.length) return true;
    if (ans[i] &gt; 0) return dfs(ans, n, i + 1, s);
    for (int d = n; d &gt; 0; --d) {
      int j = i + (d == 1 ? 0 : d);
      if ((s &amp; (1 &lt;&lt; d)) &gt; 0 || j &gt;= ans.length || ans[j] &gt; 0)
        continue;
      ans[i] = ans[j] = d;
      if (dfs(ans, n, i + 1, s | (1 &lt;&lt; d))) return true;
      ans[i] = ans[j] = 0;
    }
    return false;
  }
  
  public int[] constructDistancedSequence(int n) {    
    int[] ans = new int[n * 2 - 1];
    dfs(ans, n, 0, 0);
    return ans;
  }  
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def constructDistancedSequence(self, n: int) -&gt; List[int]:
    l = n * 2 - 1
    ans = [0] * l
    def dfs(i, s):
      if i == l: return True
      if ans[i]: return dfs(i + 1, s)
      for d in range(n, 0, -1):
        j = i + (0 if d == 1 else d)
        if s &amp; (1 &lt;&lt; d) or j &gt;= l or ans[j]: continue
        ans[i] = ans[j] = d
        if dfs(i + 1, s | (1 &lt;&lt; d)): return True
        ans[i] = ans[j] = 0
      return False
    dfs(0, 0)
    return ans</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1718-construct-the-lexicographically-largest-valid-sequence/">花花酱 LeetCode 1718. Construct the Lexicographically Largest Valid Sequence</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/searching/leetcode-1718-construct-the-lexicographically-largest-valid-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
