<?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>Search &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/searching/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Thu, 10 Apr 2025 15:01:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>Search &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 650. 2 Keys Keyboard</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-650-2-keys-keyboard/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-650-2-keys-keyboard/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 10 Apr 2025 14:44:47 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10307</guid>

					<description><![CDATA[这道题目还是可以的。每个阶段有两种选择，求最短的决策次数。有好多种不同的做法，我们一个一个来。 方法1: BFS 把问题看成求无权重图中的最短路径，BFS可以找到最优解。 我们的节点有两个状态，当前的长度，剪贴板（上次复制后）的长度。长度超过n一定无解，所以我们的状态最多只有n2种，每个状态最多拓展2个新的节点。 时间复杂度：O(n2)空间复杂度：O(n2) [crayon-67fce75d24883433100552/]]]></description>
										<content:encoded><![CDATA[
<p>这道题目还是可以的。每个阶段有两种选择，求最短的决策次数。有好多种不同的做法，我们一个一个来。</p>



<p>方法1: BFS<br><br>把问题看成求无权重图中的最短路径，BFS可以找到最优解。</p>



<p>我们的节点有两个状态，当前的长度，剪贴板（上次复制后）的长度。<br>长度超过n一定无解，所以我们的状态最多只有n<sup>2</sup>种，每个状态最多拓展2个新的节点。</p>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/2-keys.png"><img fetchpriority="high" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/2-keys.png" alt="" class="wp-image-10312" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/2-keys.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/2-keys-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/2-keys-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>时间复杂度：O(n<sup>2</sup>)<br>空间复杂度：O(n<sup>2</sup>)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minSteps(int n) {
    vector&lt;vector&lt;bool&gt;&gt; seen(n + 1, vector&lt;bool&gt;(n + 1));
    queue&lt;pair&lt;int, int&gt;&gt; q;

    auto expand = [&amp;](int len, int clip) {
      if (len &gt; n || len &gt; n || seen[len][clip]) return;
      q.emplace(len, clip);
      seen[len][clip] = true;
    };

    int steps = 0;
    expand(1, 0); // init state.
    while (!q.empty()) {
      int size = q.size();
      while (size--) {
        auto [len, clip] = q.front(); q.pop();
        if (len == n) return steps;
        expand(len, len); // copy.
        expand(len + clip, clip); // paste.
      }
      ++steps;
    }
    return -1;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-650-2-keys-keyboard/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2157. Groups of Strings</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2157-groups-of-strings/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2157-groups-of-strings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 07 Feb 2022 01:03:45 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[connected components]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[search]]></category>
		<category><![CDATA[union find]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9492</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;array of strings&#160;words. Each string consists of&#160;lowercase English letters&#160;only. No letter occurs more than once in any string of&#160;words. Two strings&#160;s1&#160;and&#160;s2&#160;are said&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array of strings&nbsp;<code>words</code>. Each string consists of&nbsp;<strong>lowercase English letters</strong>&nbsp;only. No letter occurs more than once in any string of&nbsp;<code>words</code>.</p>



<p>Two strings&nbsp;<code>s1</code>&nbsp;and&nbsp;<code>s2</code>&nbsp;are said to be&nbsp;<strong>connected</strong>&nbsp;if the set of letters of&nbsp;<code>s2</code>&nbsp;can be obtained from the set of letters of&nbsp;<code>s1</code>&nbsp;by any&nbsp;<strong>one</strong>&nbsp;of the following operations:</p>



<ul class="wp-block-list"><li>Adding exactly one letter to the set of the letters of&nbsp;<code>s1</code>.</li><li>Deleting exactly one letter from the set of the letters of&nbsp;<code>s1</code>.</li><li>Replacing exactly one letter from the set of the letters of&nbsp;<code>s1</code>&nbsp;with any letter,&nbsp;<strong>including</strong>&nbsp;itself.</li></ul>



<p>The array&nbsp;<code>words</code>&nbsp;can be divided into one or more non-intersecting&nbsp;<strong>groups</strong>. A string belongs to a group if any&nbsp;<strong>one</strong>&nbsp;of the following is true:</p>



<ul class="wp-block-list"><li>It is connected to&nbsp;<strong>at least one</strong>&nbsp;other string of the group.</li><li>It is the&nbsp;<strong>only</strong>&nbsp;string present in the group.</li></ul>



<p>Note that the strings in&nbsp;<code>words</code>&nbsp;should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique.</p>



<p>Return&nbsp;<em>an array</em>&nbsp;<code>ans</code>&nbsp;<em>of size</em>&nbsp;<code>2</code>&nbsp;<em>where:</em></p>



<ul class="wp-block-list"><li><code>ans[0]</code>&nbsp;<em>is the&nbsp;<strong>total number</strong>&nbsp;of groups</em>&nbsp;<code>words</code>&nbsp;<em>can be divided into, and</em></li><li><code>ans[1]</code>&nbsp;<em>is the&nbsp;<strong>size of the largest</strong>&nbsp;group</em>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["a","b","ab","cde"]
<strong>Output:</strong> [2,3]
<strong>Explanation:</strong>
- words[0] can be used to obtain words[1] (by replacing 'a' with 'b'), and words[2] (by adding 'b'). So words[0] is connected to words[1] and words[2].
- words[1] can be used to obtain words[0] (by replacing 'b' with 'a'), and words[2] (by adding 'a'). So words[1] is connected to words[0] and words[2].
- words[2] can be used to obtain words[0] (by deleting 'b'), and words[1] (by deleting 'a'). So words[2] is connected to words[0] and words[1].
- words[3] is not connected to any string in words.
Thus, words can be divided into 2 groups ["a","b","ab"] and ["cde"]. The size of the largest group is 3.  
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["a","ab","abc"]
<strong>Output:</strong> [1,3]
<strong>Explanation:</strong>
- words[0] is connected to words[1].
- words[1] is connected to words[0] and words[2].
- words[2] is connected to words[1].
Since all strings are connected to each other, they should be grouped together.
Thus, the size of the largest group is 3.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= words.length &lt;= 2 * 10<sup>4</sup></code></li><li><code>1 &lt;= words[i].length &lt;= 26</code></li><li><code>words[i]</code>&nbsp;consists of lowercase English letters only.</li><li>No letter occurs more than once in&nbsp;<code>words[i]</code>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Bitmask + DFS</strong></h2>



<p>Use a bitmask to represent a string. Use dfs to find connected components.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; groupStrings(vector&lt;string&gt;&amp; words) {
    unordered_map&lt;int, int&gt; m;
    for (const string&amp; w : words)
      ++m[accumulate(begin(w), end(w), 0, [](int k, char c){ return k | (1 &lt;&lt; (c - 'a')); })];
    function&lt;int(int)&gt; dfs = [&amp;](int mask) {
      auto it = m.find(mask);
      if (it == end(m)) return 0;
      int ans = it-&gt;second;      
      m.erase(it);
      for (int i = 0; i &lt; 26; ++i) {        
        ans += dfs(mask ^ (1 &lt;&lt; i));
        for (int j = i + 1; j &lt; 26; ++j)
          if ((mask &gt;&gt; i &amp; 1) != (mask &gt;&gt; j &amp; 1))
            ans += dfs(mask ^ (1 &lt;&lt; i) ^ (1 &lt;&lt; j));
      }
      return ans;
    };
    int size = 0;
    int groups = 0;
    while (!m.empty()) {
      size = max(size, dfs(begin(m)-&gt;first));
      ++groups;
    }
    return {groups, size};
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-2157-groups-of-strings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2151. Maximum Good People Based on Statements</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2151-maximum-good-people-based-on-statements/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2151-maximum-good-people-based-on-statements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 05 Feb 2022 02:13:31 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[subsets]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9477</guid>

					<description><![CDATA[There are two types of persons: The&#160;good person: The person who always tells the truth. The&#160;bad person: The person who might tell the truth and&#8230;]]></description>
										<content:encoded><![CDATA[
<p>There are two types of persons:</p>



<ul class="wp-block-list"><li>The&nbsp;<strong>good person</strong>: The person who always tells the truth.</li><li>The&nbsp;<strong>bad person</strong>: The person who might tell the truth and might lie.</li></ul>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array&nbsp;<code>statements</code>&nbsp;of size&nbsp;<code>n x n</code>&nbsp;that represents the statements made by&nbsp;<code>n</code>&nbsp;people about each other. More specifically,&nbsp;<code>statements[i][j]</code>&nbsp;could be one of the following:</p>



<ul class="wp-block-list"><li><code>0</code>&nbsp;which represents a statement made by person&nbsp;<code>i</code>&nbsp;that person&nbsp;<code>j</code>&nbsp;is a&nbsp;<strong>bad</strong>&nbsp;person.</li><li><code>1</code>&nbsp;which represents a statement made by person&nbsp;<code>i</code>&nbsp;that person&nbsp;<code>j</code>&nbsp;is a&nbsp;<strong>good</strong>&nbsp;person.</li><li><code>2</code>&nbsp;represents that&nbsp;<strong>no statement</strong>&nbsp;is made by person&nbsp;<code>i</code>&nbsp;about person&nbsp;<code>j</code>.</li></ul>



<p>Additionally, no person ever makes a statement about themselves. Formally, we have that&nbsp;<code>statements[i][i] = 2</code>&nbsp;for all&nbsp;<code>0 &lt;= i &lt; n</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of people who can be&nbsp;<strong>good</strong>&nbsp;based on the statements made by the&nbsp;</em><code>n</code><em>&nbsp;people</em>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/01/15/logic1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> statements = [[2,1,2],[1,2,2],[2,0,2]]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Each person makes a single statement.
- Person 0 states that person 1 is good.
- Person 1 states that person 0 is good.
- Person 2 states that person 1 is bad.
Let's take person 2 as the key.
- Assuming that person 2 is a good person:
    - Based on the statement made by person 2, person 1 is a bad person.
    - Now we know for sure that person 1 is bad and person 2 is good.
    - Based on the statement made by person 1, and since person 1 is bad, they could be:
        - telling the truth. There will be a contradiction in this case and this assumption is invalid.
        - lying. In this case, person 0 is also a bad person and lied in their statement.
    - <strong>Following that person 2 is a good person, there will be only one good person in the group</strong>.
- Assuming that person 2 is a bad person:
    - Based on the statement made by person 2, and since person 2 is bad, they could be:
        - telling the truth. Following this scenario, person 0 and 1 are both bad as explained before.
            - <strong>Following that person 2 is bad but told the truth, there will be no good persons in the group</strong>.
        - lying. In this case person 1 is a good person.
            - Since person 1 is a good person, person 0 is also a good person.
            - <strong>Following that person 2 is bad and lied, there will be two good persons in the group</strong>.
We can see that at most 2 persons are good in the best case, so we return 2.
Note that there is more than one way to arrive at this conclusion.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/01/15/logic2.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> statements = [[2,0],[0,2]]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Each person makes a single statement.
- Person 0 states that person 1 is bad.
- Person 1 states that person 0 is bad.
Let's take person 0 as the key.
- Assuming that person 0 is a good person:
    - Based on the statement made by person 0, person 1 is a bad person and was lying.
    - <strong>Following that person 0 is a good person, there will be only one good person in the group</strong>.
- Assuming that person 0 is a bad person:
    - Based on the statement made by person 0, and since person 0 is bad, they could be:
        - telling the truth. Following this scenario, person 0 and 1 are both bad.
            - <strong>Following that person 0 is bad but told the truth, there will be no good persons in the group</strong>.
        - lying. In this case person 1 is a good person.
            - <strong>Following that person 0 is bad and lied, there will be only one good person in the group</strong>.
We can see that at most, one person is good in the best case, so we return 1.
Note that there is more than one way to arrive at this conclusion.
</pre>



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



<ul class="wp-block-list"><li><code>n == statements.length == statements[i].length</code></li><li><code>2 &lt;= n &lt;= 15</code></li><li><code>statements[i][j]</code>&nbsp;is either&nbsp;<code>0</code>,&nbsp;<code>1</code>, or&nbsp;<code>2</code>.</li><li><code>statements[i][i] == 2</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Combination / Bitmask</strong></h2>



<p>Enumerate all subsets of n people and assume they are good people. Check whether their statements have any conflicts. We can ignore the statements from bad people since those can be either true or false and does not affect our checks.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumGood(vector&lt;vector&lt;int&gt;&gt;&amp; statements) {
    const int n = statements.size();
    auto valid = [&amp;](int s) {
      for (int i = 0; i &lt; n; ++i) {
        if (!(s &gt;&gt; i &amp; 1)) continue;
        for (int j = 0; j &lt; n; ++j) {
          const bool good = s &gt;&gt; j &amp; 1;
          if ((good &amp;&amp; statements[i][j] == 0) || (!good &amp;&amp; statements[i][j] == 1))
            return false;
        }
      }
      return true;
    };
    int ans = 0;
    for (int s = 1; s &lt; 1 &lt;&lt; n; ++s)
      if (valid(s)) ans = max(ans, __builtin_popcount(s));
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-2151-maximum-good-people-based-on-statements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2146. K Highest Ranked Items Within a Price Range</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 04 Feb 2022 01:23:04 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[grid]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[shortest path]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9458</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;2D integer array&#160;grid&#160;of size&#160;m x n&#160;that represents a map of the items in a shop. The integers in the grid represent the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array&nbsp;<code>grid</code>&nbsp;of size&nbsp;<code>m x n</code>&nbsp;that represents a map of the items in a shop. The integers in the grid represent the following:</p>



<ul class="wp-block-list"><li><code>0</code>&nbsp;represents a wall that you cannot pass through.</li><li><code>1</code>&nbsp;represents an empty cell that you can freely move to and from.</li><li>All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.</li></ul>



<p>It takes&nbsp;<code>1</code>&nbsp;step to travel between adjacent grid cells.</p>



<p>You are also given integer arrays&nbsp;<code>pricing</code>&nbsp;and&nbsp;<code>start</code>&nbsp;where&nbsp;<code>pricing = [low, high]</code>&nbsp;and&nbsp;<code>start = [row, col]</code>&nbsp;indicates that you start at the position&nbsp;<code>(row, col)</code>&nbsp;and are interested only in items with a price in the range of&nbsp;<code>[low, high]</code>&nbsp;(<strong>inclusive</strong>). You are further given an integer&nbsp;<code>k</code>.</p>



<p>You are interested in the&nbsp;<strong>positions</strong>&nbsp;of the&nbsp;<code>k</code>&nbsp;<strong>highest-ranked</strong>&nbsp;items whose prices are&nbsp;<strong>within</strong>&nbsp;the given price range. The rank is determined by the&nbsp;<strong>first</strong>&nbsp;of these criteria that is different:</p>



<ol class="wp-block-list"><li>Distance, defined as the length of the shortest path from the&nbsp;<code>start</code>&nbsp;(<strong>shorter</strong>&nbsp;distance has a higher rank).</li><li>Price (<strong>lower</strong>&nbsp;price has a higher rank, but it must be&nbsp;<strong>in the price range</strong>).</li><li>The row number (<strong>smaller</strong>&nbsp;row number has a higher rank).</li><li>The column number (<strong>smaller</strong>&nbsp;column number has a higher rank).</li></ol>



<p>Return&nbsp;<em>the&nbsp;</em><code>k</code><em>&nbsp;highest-ranked items within the price range&nbsp;<strong>sorted</strong>&nbsp;by their rank (highest to lowest)</em>. If there are fewer than&nbsp;<code>k</code>&nbsp;reachable items within the price range, return&nbsp;<em><strong>all</strong>&nbsp;of them</em>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/12/16/example1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3
<strong>Output:</strong> [[0,1],[1,1],[2,1]]
<strong>Explanation:</strong> You start at (0,0).
With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).
The ranks of these items are:
- (0,1) with distance 1
- (1,1) with distance 2
- (2,1) with distance 3
- (2,2) with distance 4
Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/12/16/example2drawio1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2
<strong>Output:</strong> [[2,1],[1,2]]
<strong>Explanation:</strong> You start at (2,3).
With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).
The ranks of these items are:
- (2,1) with distance 2, price 2
- (1,2) with distance 2, price 3
- (1,1) with distance 3
- (0,1) with distance 4
Thus, the 2 highest ranked items in the price range are (2,1) and (1,2).
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/12/30/example3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3
<strong>Output:</strong> [[2,1],[2,0]]
<strong>Explanation:</strong> You start at (0,0).
With a price range of [2,3], we can take items from (2,0) and (2,1). 
The ranks of these items are: 
- (2,1) with distance 5
- (2,0) with distance 6
Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). 
Note that k = 3 but there are only 2 reachable items within the price range.
</pre>



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



<ul class="wp-block-list"><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= m * n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= grid[i][j] &lt;= 10<sup>5</sup></code></li><li><code>pricing.length == 2</code></li><li><code>2 &lt;= low &lt;= high &lt;= 10<sup>5</sup></code></li><li><code>start.length == 2</code></li><li><code>0 &lt;= row &lt;= m - 1</code></li><li><code>0 &lt;= col &lt;= n - 1</code></li><li><code>grid[row][col] &gt; 0</code></li><li><code>1 &lt;= k &lt;= m * n</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: BFS + Sorting</strong></h2>



<p>Use BFS to collect reachable cells and sort afterwards.</p>



<p>Time complexity: O(mn + KlogK) where K = # of reachable cells.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; highestRankedKItems(vector&lt;vector&lt;int&gt;&gt;&amp; grid, vector&lt;int&gt;&amp; pricing, vector&lt;int&gt;&amp; start, int k) {
    const int m = grid.size();
    const int n = grid[0].size();    
    const vector&lt;int&gt; dirs{1, 0, -1, 0, 1};    
    vector&lt;vector&lt;int&gt;&gt; seen(m, vector&lt;int&gt;(n));
    seen[start[0]][start[1]] = 1;
    vector&lt;vector&lt;int&gt;&gt; cells;
    queue&lt;array&lt;int, 3&gt;&gt; q;
    q.push({start[0], start[1], 0});
    while (!q.empty()) {
      auto [y, x, d] = q.front(); q.pop();
      if (grid[y][x] &gt;= pricing[0] &amp;&amp; grid[y][x] &lt;= pricing[1])
          cells.push_back({d, grid[y][x], y, x});
      for (int i = 0; i &lt; 4; ++i) {
        const int tx = x + dirs[i];
        const int ty = y + dirs[i + 1];
        if (tx &lt; 0 || tx &gt;= n || ty &lt; 0 || ty &gt;= m 
            || !grid[ty][tx] || seen[ty][tx]++) continue;
        q.push({ty, tx, d + 1});
      }
    }
    sort(begin(cells), end(cells), less&lt;vector&lt;int&gt;&gt;());
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (int i = 0; i &lt; min(k, (int)(cells.size())); ++i)
      ans.push_back({cells[i][2], cells[i][3]});
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-2146-k-highest-ranked-items-within-a-price-range/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1926. Nearest Exit from Entrance in Maze</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1926-nearest-exit-from-entrance-in-maze/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1926-nearest-exit-from-entrance-in-maze/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 30 Dec 2021 11:07:41 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9285</guid>

					<description><![CDATA[You are given an&#160;m x n&#160;matrix&#160;maze&#160;(0-indexed) with empty cells (represented as&#160;'.') and walls (represented as&#160;'+'). You are also given the&#160;entrance&#160;of the maze, where&#160;entrance = [entrancerow,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an&nbsp;<code>m x n</code>&nbsp;matrix&nbsp;<code>maze</code>&nbsp;(<strong>0-indexed</strong>) with empty cells (represented as&nbsp;<code>'.'</code>) and walls (represented as&nbsp;<code>'+'</code>). You are also given the&nbsp;<code>entrance</code>&nbsp;of the maze, where&nbsp;<code>entrance = [entrance<sub>row</sub>, entrance<sub>col</sub>]</code>&nbsp;denotes the row and column of the cell you are initially standing at.</p>



<p>In one step, you can move one cell&nbsp;<strong>up</strong>,&nbsp;<strong>down</strong>,&nbsp;<strong>left</strong>, or&nbsp;<strong>right</strong>. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the&nbsp;<strong>nearest exit</strong>&nbsp;from the&nbsp;<code>entrance</code>. An&nbsp;<strong>exit</strong>&nbsp;is defined as an&nbsp;<strong>empty cell</strong>&nbsp;that is at the&nbsp;<strong>border</strong>&nbsp;of the&nbsp;<code>maze</code>. The&nbsp;<code>entrance</code>&nbsp;<strong>does not count</strong>&nbsp;as an exit.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>number of steps</strong>&nbsp;in the shortest path from the&nbsp;</em><code>entrance</code><em>&nbsp;to the nearest exit, or&nbsp;</em><code>-1</code><em>&nbsp;if no such path exists</em>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
<strong>Output:</strong> 2
<strong>Explanation:</strong> There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> maze = [[".","+"]], entrance = [0,0]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There are no exits in this maze.
</pre>



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



<ul class="wp-block-list"><li><code>maze.length == m</code></li><li><code>maze[i].length == n</code></li><li><code>1 &lt;= m, n &lt;= 100</code></li><li><code>maze[i][j]</code>&nbsp;is either&nbsp;<code>'.'</code>&nbsp;or&nbsp;<code>'+'</code>.</li><li><code>entrance.length == 2</code></li><li><code>0 &lt;= entrance<sub>row</sub>&nbsp;&lt; m</code></li><li><code>0 &lt;= entrance<sub>col</sub>&nbsp;&lt; n</code></li><li><code>entrance</code>&nbsp;will always be an empty cell.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: BFS</strong></h2>



<p>Use BFS to find the shortest path. We can re-use the board for visited array.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int nearestExit(vector&lt;vector&lt;char&gt;&gt;&amp; maze, vector&lt;int&gt;&amp; entrance) {    
    const int m = maze.size();
    const int n = maze[0].size();
    const vector&lt;int&gt; dirs{0, -1, 0, 1, 0};
    queue&lt;pair&lt;int, int&gt;&gt; q;
    q.emplace(entrance[1], entrance[0]);    
    for (int steps = 0; !q.empty(); ++steps) {      
      for (int s = q.size(); s; --s) {      
        const auto [x, y] = q.front(); q.pop();        
        if (x == 0 || x == n - 1 || y == 0 || y == m - 1)
          if (x != entrance[1] || y != entrance[0])
            return steps;
        for (int i = 0; i &lt; 4; ++i) {
          const int tx = x + dirs[i];
          const int ty = y + dirs[i + 1];
          if (tx &lt; 0 || tx &gt;= n || ty &lt; 0 || ty &gt;= m || maze[ty][tx] != '.') continue;
          maze[ty][tx] = '*';
          q.emplace(tx, ty);
        }
      }      
    }
    return -1;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-1926-nearest-exit-from-entrance-in-maze/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2081. Sum of k-Mirror Numbers</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2081-sum-of-k-mirror-numbers/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2081-sum-of-k-mirror-numbers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Nov 2021 23:51:32 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[palindrom]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8758</guid>

					<description><![CDATA[A&#160;k-mirror number&#160;is a&#160;positive&#160;integer&#160;without leading zeros&#160;that reads the same both forward and backward in base-10&#160;as well as&#160;in base-k. For example,&#160;9&#160;is a 2-mirror number. The representation of&#160;9&#160;in&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A&nbsp;<strong>k-mirror number</strong>&nbsp;is a&nbsp;<strong>positive</strong>&nbsp;integer&nbsp;<strong>without leading zeros</strong>&nbsp;that reads the same both forward and backward in base-10&nbsp;<strong>as well as</strong>&nbsp;in base-k.</p>



<ul class="wp-block-list"><li>For example,&nbsp;<code>9</code>&nbsp;is a 2-mirror number. The representation of&nbsp;<code>9</code>&nbsp;in base-10 and base-2 are&nbsp;<code>9</code>&nbsp;and&nbsp;<code>1001</code>&nbsp;respectively, which read the same both forward and backward.</li><li>On the contrary,&nbsp;<code>4</code>&nbsp;is not a 2-mirror number. The representation of&nbsp;<code>4</code>&nbsp;in base-2 is&nbsp;<code>100</code>, which does not read the same both forward and backward.</li></ul>



<p>Given the base&nbsp;<code>k</code>&nbsp;and the number&nbsp;<code>n</code>, return&nbsp;<em>the&nbsp;<strong>sum</strong>&nbsp;of the</em>&nbsp;<code>n</code>&nbsp;<em><strong>smallest</strong>&nbsp;k-mirror numbers</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 2, n = 5
<strong>Output:</strong> 25
<strong>Explanation:
</strong>The 5 smallest 2-mirror numbers and their representations in base-2 are listed as follows:
  base-10    base-2
    1          1
    3          11
    5          101
    7          111
    9          1001
Their sum = 1 + 3 + 5 + 7 + 9 = 25. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 3, n = 7
<strong>Output:</strong> 499
<strong>Explanation:
</strong>The 7 smallest 3-mirror numbers are and their representations in base-3 are listed as follows:
  base-10    base-3
    1          1
    2          2
    4          11
    8          22
    121        11111
    151        12121
    212        21212
Their sum = 1 + 2 + 4 + 8 + 121 + 151 + 212 = 499.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> k = 7, n = 17
<strong>Output:</strong> 20379000
<strong>Explanation:</strong> The 17 smallest 7-mirror numbers are:
1, 2, 3, 4, 5, 6, 8, 121, 171, 242, 292, 16561, 65656, 2137312, 4602064, 6597956, 6958596
</pre>



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



<ul class="wp-block-list"><li><code>2 &lt;= k &lt;= 9</code></li><li><code>1 &lt;= n &lt;= 30</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Generate palindromes in base-k.</strong></h2>



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

<pre class="urvanov-syntax-highlighter-plain-tag"># Author: Huahua
class Solution:
  def kMirror(self, k: int, n: int) -&gt; int:
    def getNext(x: str) -&gt; str:
      s = list(x)
      l = len(s)    
      for i in range(l // 2, l):
        if int(s[i]) + 1 &gt;= k: continue
        s[i] = s[~i] = str(int(s[i]) + 1)
        for j in range(l // 2, i): s[j] = s[~j] = &quot;0&quot;
        return &quot;&quot;.join(s)
      return &quot;1&quot; + &quot;0&quot; * (l - 1) + &quot;1&quot;
    ans = 0
    x = &quot;0&quot;
    for _ in range(n):
      while True:
        x = getNext(x)
        val = int(x, k)
        if str(val) == str(val)[::-1]: break
      ans += val
    return ans</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-2081-sum-of-k-mirror-numbers/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[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;]]></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 decoding="async" 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 class="wp-block-list"><li><code>2 &lt;= s.length &lt;= 12</code></li><li><code>s</code>&nbsp;consists of lowercase English letters only.</li></ul>



<h2 class="wp-block-heading"><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="urvanov-syntax-highlighter-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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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[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;]]></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 decoding="async" 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 decoding="async" 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 decoding="async" 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 decoding="async" 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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 2059. Minimum Operations to Convert Number</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2059-minimum-operations-to-convert-number/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2059-minimum-operations-to-convert-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 05 Nov 2021 06:00:14 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8666</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;containing&#160;distinct&#160;numbers, an integer&#160;start, and an integer&#160;goal. There is an integer&#160;x&#160;that is initially set to&#160;start, and you want to perform operations on&#160;x&#160;such&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;containing&nbsp;<strong>distinct</strong>&nbsp;numbers, an integer&nbsp;<code>start</code>, and an integer&nbsp;<code>goal</code>. There is an integer&nbsp;<code>x</code>&nbsp;that is initially set to&nbsp;<code>start</code>, and you want to perform operations on&nbsp;<code>x</code>&nbsp;such that it is converted to&nbsp;<code>goal</code>. You can perform the following operation repeatedly on the number&nbsp;<code>x</code>:</p>



<p>If&nbsp;<code>0 &lt;= x &lt;= 1000</code>, then for any index&nbsp;<code>i</code>&nbsp;in the array (<code>0 &lt;= i &lt; nums.length</code>), you can set&nbsp;<code>x</code>&nbsp;to any of the following:</p>



<ul class="wp-block-list"><li><code>x + nums[i]</code></li><li><code>x - nums[i]</code></li><li><code>x ^ nums[i]</code>&nbsp;(bitwise-XOR)</li></ul>



<p>Note that you can use each&nbsp;<code>nums[i]</code>&nbsp;any number of times in any order. Operations that set&nbsp;<code>x</code>&nbsp;to be out of the range&nbsp;<code>0 &lt;= x &lt;= 1000</code>&nbsp;are valid, but no more operations can be done afterward.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of operations needed to convert&nbsp;</em><code>x = start</code><em>&nbsp;into&nbsp;</em><code>goal</code><em>, and&nbsp;</em><code>-1</code><em>&nbsp;if it is not possible</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,3], start = 6, goal = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
We can go from 6 → 7 → 4 with the following 2 operations.
- 6 ^ 1 = 7
- 7 ^ 3 = 4
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,4,12], start = 2, goal = 12
<strong>Output:</strong> 2
<strong>Explanation:</strong>
We can go from 2 → 14 → 12 with the following 2 operations.
- 2 + 12 = 14
- 14 - 2 = 12
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,5,7], start = 0, goal = -4
<strong>Output:</strong> 2
<strong>Explanation:</strong>
We can go from 0 → 3 → -4 with the following 2 operations. 
- 0 + 3 = 3
- 3 - 7 = -4
Note that the last operation sets x out of the range 0 &lt;= x &lt;= 1000, which is valid.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,8,16], start = 0, goal = 1
<strong>Output:</strong> -1
<strong>Explanation:</strong>
There is no way to convert 0 into 1.</pre>



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



<pre class="urvanov-syntax-highlighter-plain-tag">&lt;strong&gt;Input:&lt;/strong&gt; nums = [1], start = 0, goal = 3
&lt;strong&gt;Output:&lt;/strong&gt; 3
&lt;strong&gt;Explanation:&lt;/strong&gt; 
We can go from 0 &rarr; 1 &rarr; 2 &rarr; 3 with the following 3 operations. 
- 0 + 1 = 1 
- 1 + 1 = 2
- 2 + 1 = 3</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 1000</code></li><li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i], goal &lt;= 10<sup>9</sup></code></li><li><code>0 &lt;= start &lt;= 1000</code></li><li><code>start != goal</code></li><li>All the integers in&nbsp;<code>nums</code>&nbsp;are distinct.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: BFS</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minimumOperations(vector&lt;int&gt;&amp; nums, int start, int goal) {
    vector&lt;int&gt; seen(1001);
    queue&lt;int&gt; q{{start}};  
    for (int ans = 1, s = 1; !q.empty(); ++ans, s = q.size()) {
      while (s--) {
        int x = q.front(); q.pop();
        for (int n : nums)
          for (int t : {x + n, x - n, x ^ n})
            if (t == goal) 
              return ans;
            else if (t &lt; 0 || t &gt; 1000 || seen[t]++)
              continue;
            else
              q.push(t);
      }
    }
    return -1;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-2059-minimum-operations-to-convert-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2048. Next Greater Numerically Balanced Number</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2048-next-greater-numerically-balanced-number/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2048-next-greater-numerically-balanced-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 26 Oct 2021 03:10:37 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8642</guid>

					<description><![CDATA[An integer&#160;x&#160;is&#160;numerically balanced&#160;if for every digit&#160;d&#160;in the number&#160;x, there are&#160;exactly&#160;d&#160;occurrences of that digit in&#160;x. Given an integer&#160;n, return&#160;the&#160;smallest numerically balanced&#160;number&#160;strictly greater&#160;than&#160;n. Example 1: Input: n&#8230;]]></description>
										<content:encoded><![CDATA[
<p>An integer&nbsp;<code>x</code>&nbsp;is&nbsp;<strong>numerically balanced</strong>&nbsp;if for every digit&nbsp;<code>d</code>&nbsp;in the number&nbsp;<code>x</code>, there are&nbsp;<strong>exactly</strong>&nbsp;<code>d</code>&nbsp;occurrences of that digit in&nbsp;<code>x</code>.</p>



<p>Given an integer&nbsp;<code>n</code>, return&nbsp;<em>the&nbsp;<strong>smallest numerically balanced</strong>&nbsp;number&nbsp;<strong>strictly greater</strong>&nbsp;than&nbsp;</em><code>n</code><em>.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 1
<strong>Output:</strong> 22
<strong>Explanation:</strong> 
22 is numerically balanced since:
- The digit 2 occurs 2 times. 
It is also the smallest numerically balanced number strictly greater than 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 1000
<strong>Output:</strong> 1333
<strong>Explanation:</strong> 
1333 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times. 
It is also the smallest numerically balanced number strictly greater than 1000.
Note that 1022 cannot be the answer because 0 appeared more than 0 times.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3000
<strong>Output:</strong> 3133
<strong>Explanation:</strong> 
3133 is numerically balanced since:
- The digit 1 occurs 1 time.
- The digit 3 occurs 3 times.
It is also the smallest numerically balanced number strictly greater than 3000.
</pre>



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



<ul class="wp-block-list"><li><code>0 &lt;= n &lt;= 10<sup>6</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Permutation</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int nextBeautifulNumber(int n) {
    const string t = to_string(n);
    vector&lt;int&gt; nums{1,
                     22,
                     122, 333,
                     1333, 4444,
                     14444, 22333, 55555,
                     122333, 155555, 224444, 666666};
    int ans = 1224444;
    for (int num : nums) {
      string s = to_string(num);
      if (s.size() &lt; t.size()) continue;
      else if (s.size() &gt; t.size()) {
        ans = min(ans, num);
      } else { // same length 
        do {
          if (s &gt; t) ans = min(ans, stoi(s));
        } while (next_permutation(begin(s), end(s)));
      }
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-2048-next-greater-numerically-balanced-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-2044-count-number-of-maximum-bitwise-or-subsets/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-2044-count-number-of-maximum-bitwise-or-subsets/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 18 Oct 2021 03:54:32 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8610</guid>

					<description><![CDATA[Given an integer array&#160;nums, find the&#160;maximum&#160;possible&#160;bitwise OR&#160;of a subset of&#160;nums&#160;and return&#160;the&#160;number of different non-empty subsets&#160;with the maximum bitwise OR. An array&#160;a&#160;is a&#160;subset&#160;of an array&#160;b&#160;if&#160;a&#160;can be&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>nums</code>, find the&nbsp;<strong>maximum</strong>&nbsp;possible&nbsp;<strong>bitwise OR</strong>&nbsp;of a subset of&nbsp;<code>nums</code>&nbsp;and return&nbsp;<em>the&nbsp;<strong>number of different non-empty subsets</strong>&nbsp;with the maximum bitwise OR</em>.</p>



<p>An array&nbsp;<code>a</code>&nbsp;is a&nbsp;<strong>subset</strong>&nbsp;of an array&nbsp;<code>b</code>&nbsp;if&nbsp;<code>a</code>&nbsp;can be obtained from&nbsp;<code>b</code>&nbsp;by deleting some (possibly zero) elements of&nbsp;<code>b</code>. Two subsets are considered&nbsp;<strong>different</strong>&nbsp;if the indices of the elements chosen are different.</p>



<p>The bitwise OR of an array&nbsp;<code>a</code>&nbsp;is equal to&nbsp;<code>a[0]&nbsp;<strong>OR</strong>&nbsp;a[1]&nbsp;<strong>OR</strong>&nbsp;...&nbsp;<strong>OR</strong>&nbsp;a[a.length - 1]</code>&nbsp;(<strong>0-indexed</strong>).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:
- [3]
- [3,1]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,2,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> All non-empty subsets of [2,2,2] have a bitwise OR of 2. There are 2<sup>3</sup> - 1 = 7 total subsets.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,1,5]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The maximum possible bitwise OR of a subset is 7. There are 6 subsets with a bitwise OR of 7:
- [3,5]
- [3,1,5]
- [3,2,5]
- [3,2,1,5]
- [2,5]
- [2,1,5]</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 16</code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Brute Force</strong></h2>



<p>Try all possible subsets</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int countMaxOrSubsets(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int max_or = 0;
    int count = 0;
    for (int s = 0; s &lt; 1 &lt;&lt; n; ++s) {
      int cur_or = 0;
      for (int i = 0; i &lt; n; ++i)
        if (s &gt;&gt; i &amp; 1) cur_or |= nums[i];
      if (cur_or &gt; max_or) {
        max_or = cur_or;
        count = 1;
      } else if (cur_or == max_or) {
        ++count;
      }
    }
    return count;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-2044-count-number-of-maximum-bitwise-or-subsets/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[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;]]></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 class="wp-block-list"><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 class="wp-block-list"><li><code>1 &lt;= s.length &lt;= 20</code></li><li><code>s</code>&nbsp;only consists of digits.</li></ul>



<h2 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 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[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;]]></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 decoding="async" 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 decoding="async" 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 class="wp-block-list"><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 class="wp-block-heading"><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="urvanov-syntax-highlighter-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>
]]></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 1765. Map of Highest Peak</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1765-map-of-highest-peak/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1765-map-of-highest-peak/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Feb 2021 05:19:36 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[BFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[shortest path]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8135</guid>

					<description><![CDATA[You are given an integer matrix&#160;isWater&#160;of size&#160;m x n&#160;that represents a map of&#160;land&#160;and&#160;water&#160;cells. If&#160;isWater[i][j] == 0, cell&#160;(i, j)&#160;is a&#160;land&#160;cell. If&#160;isWater[i][j] == 1, cell&#160;(i, j)&#160;is a&#160;water&#160;cell.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer matrix&nbsp;<code>isWater</code>&nbsp;of size&nbsp;<code>m x n</code>&nbsp;that represents a map of&nbsp;<strong>land</strong>&nbsp;and&nbsp;<strong>water</strong>&nbsp;cells.</p>



<ul class="wp-block-list"><li>If&nbsp;<code>isWater[i][j] == 0</code>, cell&nbsp;<code>(i, j)</code>&nbsp;is a&nbsp;<strong>land</strong>&nbsp;cell.</li><li>If&nbsp;<code>isWater[i][j] == 1</code>, cell&nbsp;<code>(i, j)</code>&nbsp;is a&nbsp;<strong>water</strong>&nbsp;cell.</li></ul>



<p>You must assign each cell a height in a way that follows these rules:</p>



<ul class="wp-block-list"><li>The height of each cell must be non-negative.</li><li>If the cell is a&nbsp;<strong>water</strong>&nbsp;cell, its height must be&nbsp;<code>0</code>.</li><li>Any two adjacent cells must have an absolute height difference of&nbsp;<strong>at most</strong>&nbsp;<code>1</code>. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).</li></ul>



<p>Find an assignment of heights such that the maximum height in the matrix is&nbsp;<strong>maximized</strong>.</p>



<p>Return&nbsp;<em>an integer matrix&nbsp;</em><code>height</code><em>&nbsp;of size&nbsp;</em><code>m x n</code><em>&nbsp;where&nbsp;</em><code>height[i][j]</code><em>&nbsp;is cell&nbsp;</em><code>(i, j)</code><em>&#8216;s height. If there are multiple solutions, return&nbsp;<strong>any</strong>&nbsp;of them</em>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82045-am.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> isWater = [[0,1],[0,0]]
<strong>Output:</strong> [[1,0],[2,1]]
<strong>Explanation:</strong> The image shows the assigned heights of each cell.
The blue cell is the water cell, and the green cells are the land cells.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/01/10/screenshot-2021-01-11-at-82050-am.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> isWater = [[0,0,1],[1,0,0],[0,0,0]]
<strong>Output:</strong> [[1,1,0],[0,1,1],[1,2,2]]
<strong>Explanation:</strong> A height of 2 is the maximum possible height of any assignment.
Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted.
</pre>



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



<ul class="wp-block-list"><li><code>m == isWater.length</code></li><li><code>n == isWater[i].length</code></li><li><code>1 &lt;= m, n &lt;= 1000</code></li><li><code>isWater[i][j]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li><li>There is at least&nbsp;<strong>one</strong>&nbsp;water cell.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: BFS</strong></h2>



<p>h[y][x] = min distance of (x, y) to any water cell.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; highestPeak(vector&lt;vector&lt;int&gt;&gt;&amp; isWater) {
    const int m = isWater.size();
    const int n = isWater[0].size();
    vector&lt;vector&lt;int&gt;&gt; ans(m, vector&lt;int&gt;(n, INT_MIN));
    queue&lt;pair&lt;int, int&gt;&gt; q;
    for (int y = 0; y &lt; m; ++y)
      for (int x = 0; x &lt; n; ++x)
        if (isWater[y][x]) {
          q.emplace(x, y);
          ans[y][x] = 0;
        }
    const vector&lt;int&gt; dirs{0, -1, 0, 1, 0};    
    while (!q.empty()) {
      const auto [cx, cy] = q.front();
      q.pop();
      for (int i = 0; i &lt; 4; ++i) {
        const int x = cx + dirs[i];
        const int y = cy + dirs[i + 1];
        if (x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= m) continue;
        if (ans[y][x] != INT_MIN) continue;
        ans[y][x] = ans[cy][cx] + 1;
        q.emplace(x, y);
      }      
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-1765-map-of-highest-peak/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[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;]]></description>
										<content:encoded><![CDATA[
<p>Given an integer&nbsp;<code>n</code>, find a sequence that satisfies all of the following:</p>



<ul class="wp-block-list"><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 class="wp-block-list"><li><code>1 &lt;= n &lt;= 20</code></li></ul>



<h2 class="wp-block-heading"><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="urvanov-syntax-highlighter-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="urvanov-syntax-highlighter-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="urvanov-syntax-highlighter-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>
]]></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>
