<?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>permutation Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/permutation/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/permutation/</link>
	<description></description>
	<lastBuildDate>Tue, 26 Oct 2021 03:11:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>permutation Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/permutation/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2048-next-greater-numerically-balanced-number/">花花酱 LeetCode 2048. Next Greater Numerically Balanced Number</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>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><li><code>0 &lt;= n &lt;= 10<sup>6</sup></code></li></ul>



<h2><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-2048-next-greater-numerically-balanced-number/">花花酱 LeetCode 2048. Next Greater Numerically Balanced Number</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-2048-next-greater-numerically-balanced-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1879. Minimum XOR Sum of Two Arrays</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1879-minimum-xor-sum-of-two-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1879-minimum-xor-sum-of-two-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 07 Aug 2021 07:17:29 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[permutation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8509</guid>

					<description><![CDATA[<p>You are given two integer arrays&#160;nums1&#160;and&#160;nums2&#160;of length&#160;n. The&#160;XOR sum&#160;of the two integer arrays is&#160;(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n -&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1879-minimum-xor-sum-of-two-arrays/">花花酱 LeetCode 1879. Minimum XOR Sum of Two Arrays</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 integer arrays&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>&nbsp;of length&nbsp;<code>n</code>.</p>



<p>The&nbsp;<strong>XOR sum</strong>&nbsp;of the two integer arrays is&nbsp;<code>(nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1])</code>&nbsp;(<strong>0-indexed</strong>).</p>



<ul><li>For example, the&nbsp;<strong>XOR sum</strong>&nbsp;of&nbsp;<code>[1,2,3]</code>&nbsp;and&nbsp;<code>[3,2,1]</code>&nbsp;is equal to&nbsp;<code>(1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4</code>.</li></ul>



<p>Rearrange the elements of&nbsp;<code>nums2</code>&nbsp;such that the resulting&nbsp;<strong>XOR sum</strong>&nbsp;is&nbsp;<strong>minimized</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>XOR sum</strong>&nbsp;after the rearrangement</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,2], nums2 = [2,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Rearrange <code>nums2</code> so that it becomes <code>[3,2]</code>.
The XOR sum is (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,0,3], nums2 = [5,3,4]
<strong>Output:</strong> 8
<strong>Explanation:</strong> Rearrange <code>nums2</code> so that it becomes <code>[5,4,3]</code>. 
The XOR sum is (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8.
</pre>



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



<ul><li><code>n == nums1.length</code></li><li><code>n == nums2.length</code></li><li><code>1 &lt;= n &lt;= 14</code></li><li><code>0 &lt;= nums1[i], nums2[i] &lt;= 10<sup>7</sup></code></li></ul>



<h2><strong>Solution: DP / Permutation to combination</strong></h2>



<p>dp[s] := min xor sum by using a subset of nums2 (presented by a binary string s) xor with nums1[0:|s|].</p>



<p>Time complexity: O(n*2<sup>n</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 minimumXORSum(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    const int n = nums1.size();
    vector&lt;int&gt; dp(1 &lt;&lt; n, INT_MAX);
    dp[0] = 0;
    for (int s = 0; s &lt; 1 &lt;&lt; n; ++s) {
      int index = __builtin_popcount(s);
      for (int i = 0; i &lt; n; ++i) {
        if (s &amp; (1 &lt;&lt; i)) continue;
        dp[s | (1 &lt;&lt; i)] = min(dp[s | (1 &lt;&lt; i)],
                               dp[s] + (nums1[index] ^ nums2[i]));
      }
    }    
    return dp.back();
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1879-minimum-xor-sum-of-two-arrays/">花花酱 LeetCode 1879. Minimum XOR Sum of Two Arrays</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-1879-minimum-xor-sum-of-two-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 May 2021 05:06:28 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8436</guid>

					<description><![CDATA[<p>You are given a string&#160;num, representing a large integer, and an integer&#160;k. We call some integer&#160;wonderful&#160;if it is a&#160;permutation&#160;of the digits in&#160;num&#160;and is&#160;greater in value&#160;than&#160;num.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number/">花花酱 LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number</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>num</code>, representing a large integer, and an integer&nbsp;<code>k</code>.</p>



<p>We call some integer&nbsp;<strong>wonderful</strong>&nbsp;if it is a&nbsp;<strong>permutation</strong>&nbsp;of the digits in&nbsp;<code>num</code>&nbsp;and is&nbsp;<strong>greater in value</strong>&nbsp;than&nbsp;<code>num</code>. There can be many wonderful integers. However, we only care about the&nbsp;<strong>smallest-valued</strong>&nbsp;ones.</p>



<ul><li>For example, when&nbsp;<code>num = "5489355142"</code>:<ul><li>The 1<sup>st</sup>&nbsp;smallest wonderful integer is&nbsp;<code>"5489355214"</code>.</li><li>The 2<sup>nd</sup>&nbsp;smallest wonderful integer is&nbsp;<code>"5489355241"</code>.</li><li>The 3<sup>rd</sup>&nbsp;smallest wonderful integer is&nbsp;<code>"5489355412"</code>.</li><li>The 4<sup>th</sup>&nbsp;smallest wonderful integer is&nbsp;<code>"5489355421"</code>.</li></ul></li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum number of adjacent digit swaps</strong>&nbsp;that needs to be applied to&nbsp;</em><code>num</code><em>&nbsp;to reach the&nbsp;</em><code>k<sup>th</sup></code><em><strong>&nbsp;smallest wonderful</strong>&nbsp;integer</em>.</p>



<p>The tests are generated in such a way that&nbsp;<code>k<sup>th</sup></code>&nbsp;smallest wonderful integer exists.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "5489355142", k = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The 4<sup>th</sup> smallest wonderful number is "5489355421". To get this number:
- Swap index 7 with index 8: "5489355142" -&gt; "5489355412"
- Swap index 8 with index 9: "5489355412" -&gt; "5489355421"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "11112", k = 4
<strong>Output:</strong> 4
<strong>Explanation:</strong> The 4<sup>th</sup> smallest wonderful number is "21111". To get this number:
- Swap index 3 with index 4: "11112" -&gt; "11121"
- Swap index 2 with index 3: "11121" -&gt; "11211"
- Swap index 1 with index 2: "11211" -&gt; "12111"
- Swap index 0 with index 1: "12111" -&gt; "21111"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = "00123", k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The 1<sup>st</sup> smallest wonderful number is "00132". To get this number:
- Swap index 3 with index 4: "00123" -&gt; "00132"
</pre>



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



<ul><li><code>2 &lt;= num.length &lt;= 1000</code></li><li><code>1 &lt;= k &lt;= 1000</code></li><li><code>num</code>&nbsp;only consists of digits.</li></ul>



<h2><strong>Solution: Next Permutation + Greedy</strong></h2>



<p>Time complexity: O(k*n + n^2)<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:
  int getMinSwaps(string s, int k) {
    string t(s);
    while (k--) next_permutation(begin(t), end(t));
    const int n = s.length();
    int ans = 0;
    for (int i = 0; i &lt; n; ++i) {
      if (s[i] == t[i]) continue;
      for (int j = i + 1; j &lt; n; ++j) {
        if (s[i] != t[j]) continue;
        ans += j - i;
        t = t.substr(0, i + 1) + t.substr(i, j - i) + t.substr(j + 1);
        break;
      }
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number/">花花酱 LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number</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/greedy/leetcode-1850-minimum-adjacent-swaps-to-reach-the-kth-smallest-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1830. Minimum Number of Operations to Make String Sorted</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1830-minimum-number-of-operations-to-make-string-sorted/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1830-minimum-number-of-operations-to-make-string-sorted/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 18 Apr 2021 16:18:06 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8367</guid>

					<description><![CDATA[<p>You are given a string&#160;s&#160;(0-indexed)​​​​​​. You are asked to perform the following operation on&#160;s​​​​​​ until you get a sorted string: Find&#160;the largest index&#160;i&#160;such that&#160;1 &#60;=&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1830-minimum-number-of-operations-to-make-string-sorted/">花花酱 LeetCode 1830. Minimum Number of Operations to Make String Sorted</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;(<strong>0-indexed</strong>)​​​​​​. You are asked to perform the following operation on&nbsp;<code>s</code>​​​​​​ until you get a sorted string:</p>



<ol><li>Find&nbsp;<strong>the largest index</strong>&nbsp;<code>i</code>&nbsp;such that&nbsp;<code>1 &lt;= i &lt; s.length</code>&nbsp;and&nbsp;<code>s[i] &lt; s[i - 1]</code>.</li><li>Find&nbsp;<strong>the largest index</strong>&nbsp;<code>j</code>&nbsp;such that&nbsp;<code>i &lt;= j &lt; s.length</code>&nbsp;and&nbsp;<code>s[k] &lt; s[i - 1]</code>&nbsp;for all the possible values of&nbsp;<code>k</code>&nbsp;in the range&nbsp;<code>[i, j]</code>&nbsp;inclusive.</li><li>Swap the two characters at indices&nbsp;<code>i - 1</code>​​​​ and&nbsp;<code>j</code>​​​​​.</li><li>Reverse the suffix starting at index&nbsp;<code>i</code>​​​​​​.</li></ol>



<p>Return&nbsp;<em>the number of operations needed to make the string sorted.</em>&nbsp;Since the answer can be too large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "cba"
<strong>Output:</strong> 5
<strong>Explanation:</strong> The simulation goes as follows:
Operation 1: i=2, j=2. Swap s[1] and s[2] to get s="cab", then reverse the suffix starting at 2. Now, s="cab".
Operation 2: i=1, j=2. Swap s[0] and s[2] to get s="bac", then reverse the suffix starting at 1. Now, s="bca".
Operation 3: i=2, j=2. Swap s[1] and s[2] to get s="bac", then reverse the suffix starting at 2. Now, s="bac".
Operation 4: i=1, j=1. Swap s[0] and s[1] to get s="abc", then reverse the suffix starting at 1. Now, s="acb".
Operation 5: i=2, j=2. Swap s[1] and s[2] to get s="abc", then reverse the suffix starting at 2. Now, s="abc".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aabaa"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The simulation goes as follows:
Operation 1: i=3, j=4. Swap s[2] and s[4] to get s="aaaab", then reverse the substring starting at 3. Now, s="aaaba".
Operation 2: i=4, j=4. Swap s[3] and s[4] to get s="aaaab", then reverse the substring starting at 4. Now, s="aaaab".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "cdbea"
<strong>Output:</strong> 63</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcodeleetcodeleetcode"
<strong>Output:</strong> 982157772
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 3000</code></li><li><code>s</code>​​​​​​ consists only of lowercase English letters.</li></ul>



<h2><strong>Solution: Math</strong></h2>



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



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

<pre class="crayon-plain-tag">constexpr int kMod = 1e9 + 7;
int64_t powm(int64_t b, int64_t p) {
  int64_t ans = 1;
  while (p) {
    if (p &amp; 1) ans = (ans * b) % kMod;
    b = (b * b) % kMod;
    p &gt;&gt;= 1;
  }
  return ans;
}

class Solution {
public:
  int makeStringSorted(string s) {
    const int n = s.length();    
    vector&lt;int64_t&gt; fact(n + 1, 1);
    vector&lt;int64_t&gt; inv(n + 1, 1);    
    
    for (int i = 1; i &lt;= n; ++i) {
      fact[i] = (fact[i - 1] * i) % kMod;
      inv[i] = powm(fact[i], kMod - 2);
    }
    
    int64_t ans = 0;
    vector&lt;int&gt; freq(26);
    for (int i = n - 1; i &gt;= 0; --i) {
      const int idx = s[i] - 'a';
      ++freq[idx];
      int64_t cur = accumulate(begin(freq), begin(freq) + idx, 0ll) *
                      fact[n - i - 1] % kMod;
      for (int f : freq)
        cur = cur * inv[f] % kMod;      
      ans = (ans + cur) % kMod;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1830-minimum-number-of-operations-to-make-string-sorted/">花花酱 LeetCode 1830. Minimum Number of Operations to Make String Sorted</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/math/leetcode-1830-minimum-number-of-operations-to-make-string-sorted/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 1806. Minimum Number of Operations to Reinitialize a Permutation</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1806-minimum-number-of-operations-to-reinitialize-a-permutation/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1806-minimum-number-of-operations-to-reinitialize-a-permutation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Mar 2021 04:56:23 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8284</guid>

					<description><![CDATA[<p>You are given an&#160;even&#160;integer&#160;n​​​​​​. You initially have a permutation&#160;perm&#160;of size&#160;n​​ where&#160;perm[i] == i​&#160;(0-indexed)​​​​. In one operation, you will create a new array&#160;arr, and for each&#160;i:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1806-minimum-number-of-operations-to-reinitialize-a-permutation/">花花酱 LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation</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 an&nbsp;<strong>even</strong>&nbsp;integer&nbsp;<code>n</code>​​​​​​. You initially have a permutation&nbsp;<code>perm</code>&nbsp;of size&nbsp;<code>n</code>​​ where&nbsp;<code>perm[i] == i</code>​&nbsp;<strong>(0-indexed)</strong>​​​​.</p>



<p>In one operation, you will create a new array&nbsp;<code>arr</code>, and for each&nbsp;<code>i</code>:</p>



<ul><li>If&nbsp;<code>i % 2 == 0</code>, then&nbsp;<code>arr[i] = perm[i / 2]</code>.</li><li>If&nbsp;<code>i % 2 == 1</code>, then&nbsp;<code>arr[i] = perm[n / 2 + (i - 1) / 2]</code>.</li></ul>



<p>You will then assign&nbsp;<code>arr</code>​​​​ to&nbsp;<code>perm</code>.</p>



<p>Return&nbsp;<em>the minimum&nbsp;<strong>non-zero</strong>&nbsp;number of operations you need to perform on&nbsp;</em><code>perm</code><em>&nbsp;to return the permutation to its initial value.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> prem = [0,1] initially.
After the 1<sup>st</sup> operation, prem = [0,1]
So it takes only 1 operation.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> prem = [0,1,2,3] initially.
After the 1<sup>st</sup> operation, prem = [0,2,1,3]
After the 2<sup>nd</sup> operation, prem = [0,1,2,3]
So it takes only 2 operations.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 6
<strong>Output:</strong> 4
</pre>



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



<ul><li><code>2 &lt;= n &lt;= 1000</code></li><li><code>n</code>​​​​​​ is even.</li></ul>



<h2><strong>Solution: Brute Force / Simulation</strong></h2>



<p>Time complexity: O(n<sup>2</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 reinitializePermutation(int n) {
    vector&lt;int&gt; perm(n);
    vector&lt;int&gt; arr(n);
    for (int i = 0; i &lt; n; ++i) perm[i] = i;
    int ans = 0;
    bool flag = true;
    while (flag &amp;&amp; ++ans) {
      flag = false;
      for (int i = 0; i &lt; n; ++i) {
        arr[i] = i &amp; 1 ? perm[n / 2 + (i - 1) / 2] : perm[i / 2];
        flag |= arr[i] != i;        
      }
      swap(perm, arr);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/simulation/leetcode-1806-minimum-number-of-operations-to-reinitialize-a-permutation/">花花酱 LeetCode 1806. Minimum Number of Operations to Reinitialize a Permutation</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/simulation/leetcode-1806-minimum-number-of-operations-to-reinitialize-a-permutation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Jun 2020 05:18:59 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[probability]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6867</guid>

					<description><![CDATA[<p>Given&#160;2n&#160;balls of&#160;k&#160;distinct colors. You will be given an integer array&#160;balls&#160;of size&#160;k&#160;where&#160;balls[i]&#160;is the number of balls of color&#160;i.&#160; All the balls will be&#160;shuffled uniformly at random,&#160;then&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/">花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls - 刷题找工作 EP332" width="500" height="375" src="https://www.youtube.com/embed/EZS6E6swOsY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given&nbsp;<code>2n</code>&nbsp;balls of&nbsp;<code>k</code>&nbsp;distinct colors. You will be given an integer array&nbsp;<code>balls</code>&nbsp;of size&nbsp;<code>k</code>&nbsp;where&nbsp;<code>balls[i]</code>&nbsp;is the number of balls of color&nbsp;<code>i</code>.&nbsp;</p>



<p>All the balls will be&nbsp;<strong>shuffled uniformly at random</strong>,&nbsp;then we will distribute the first&nbsp;<code>n</code>&nbsp;balls to the first box and the remaining&nbsp;<code>n</code>&nbsp;balls to the other box (Please read the explanation of the second example carefully).</p>



<p>Please note that the two boxes are considered different. For example, if we have two balls of colors&nbsp;<code>a</code>&nbsp;and&nbsp;<code>b</code>, and two boxes&nbsp;<code>[]</code>&nbsp;and&nbsp;<code>()</code>, then the distribution&nbsp;<code>[a] (b)</code>&nbsp;is considered different than the distribution&nbsp;<code>[b] (a)&nbsp;</code>(Please read the explanation of the first&nbsp;example carefully).</p>



<p>We want to&nbsp;<em>calculate the probability</em>&nbsp;that the two boxes have the same number of distinct balls.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [1,1]
<strong>Output:</strong> 1.00000
<strong>Explanation:</strong> Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [2,1,1]
<strong>Output:</strong> 0.66667
<strong>Explanation:</strong> We have the set of balls [1, 1, 2, 3]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equale probability (i.e. 1/12):
[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
After that we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [1,2,1,2]
<strong>Output:</strong> 0.60000
<strong>Explanation:</strong> The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [3,2,1]
<strong>Output:</strong> 0.30000
<strong>Explanation:</strong> The set of balls is [1, 1, 1, 2, 2, 3]. It is hard to display all the 60 possible random shuffles of this set but it is easy to check that 18 of them will have the same number of distinct colors in each box.
Probability = 18 / 60 = 0.3
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> balls = [6,6,6,6,6,6]
<strong>Output:</strong> 0.90327
</pre>



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



<ul><li><code>1 &lt;= balls.length &lt;= 8</code></li><li><code>1 &lt;= balls[i] &lt;= 6</code></li><li><code>sum(balls)</code>&nbsp;is even.</li><li>Answers within&nbsp;<code>10^-5</code>&nbsp;of the actual value will be accepted as correct.</li></ul>



<h2><strong>Solution 0: Permutation</strong> (<strong>TLE</strong>)</h2>



<p>Enumerate all permutations of the balls, count valid ones and divide that by the total.</p>



<p>Time complexity: O((8*6)!) = O(48!) <br>After deduplication: O(48!/(6!)^8) ~ 1.7e38<br>Space complexity: O(8*6)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, TLE 4/21 passed
class Solution {
public:
  double getProbability(vector&lt;int&gt;&amp; balls) {
    const int k = balls.size();
    vector&lt;int&gt; bs;
    for (int i = 0; i &lt; k; ++i)
      for (int j = 0; j &lt; balls[i]; ++j)
        bs.push_back(i);
    const int n = bs.size();
    double total = 0.0;
    double valid = 0.0;
    // d : depth
    // used : bitmap of bs's usage
    // c1: bitmap of colors of box1
    // c2: bitmap of colors of box1
    function&lt;void(int, long, int, int)&gt; dfs = [&amp;](int d, long used, int c1, int c2) {    
      if (d == n) {          
        total += 1;
        valid += __builtin_popcount(c1) == __builtin_popcount(c2);                
        return;
      }
      for (int i = 0; i &lt; n; ++i) {
        if (used &amp; (1L &lt;&lt; i)) continue;
        // Deduplication.
        if (i &gt; 0 &amp;&amp; bs[i] == bs[i - 1] &amp;&amp; !(used &amp; (1L &lt;&lt; (i - 1)))) continue;        
        int tc1 = (d &lt; n / 2) ? (c1 | (1 &lt;&lt; bs[i])) : c1;
        int tc2 = (d &lt; n / 2) ? c2 : (c2 | (1 &lt;&lt; bs[i]));
        dfs(d + 1, used | (1L &lt;&lt; i), tc1, tc2);
      }
    };
    dfs(0, 0, 0, 0);    
    return valid / total;
  }
};</pre>
</div></div>



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



<p>For each color, put n_i balls into box1, the left t_i &#8211; n_i balls go to box2.<br>permutations = fact(n//2) / PROD(fact(n_i)) * fact(n//2) * PROD(fact(t_i &#8211; n_i))<br>E.g<br>balls = [1&#215;2, 2&#215;6, 3&#215;4]<br>One possible combination:<br>box1: 1 22 333<br>box2: 1 2222 3<br>permutations = 6! / (1! * 2! * 3!) * 6! / (1! * 4! * 1!) = 1800</p>



<p>Time complexity: O((t+1)^k) = O(7^8)<br>Space complexity: O(k + (t*k)) = O(8 + 48)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double getProbability(vector&lt;int&gt;&amp; balls) {
    const int n = accumulate(begin(balls), end(balls), 0);
    const int k = balls.size();        
    double total = 0.0;
    double valid = 0.0;
    vector&lt;double&gt; fact(50, 1.0);
    for (int i = 1; i &lt; fact.size(); ++i)
      fact[i] = fact[i - 1] * i;
    // d: depth
    // b1, b2: # of balls in box1, box2
    // c1, c2: # of distinct colors in box1, box2
    // p1, p2: # permutations of duplicate balls in box1, box2
    function&lt;void(int, int, int, int, int, double, double)&gt; dfs = [&amp;]
      (int d, int b1, int b2, int c1, int c2, double p1, double p2) {
      if (b1 &gt; n / 2 || b2 &gt; n / 2) return;
      if (d == k) {
        const double count = fact[b1] / p1 * fact[b2] / p2;
        total += count;
        valid += count * (c1 == c2);
        return;
      }
      for (int s1 = 0; s1 &lt;= balls[d]; ++s1) {
        const int s2 = balls[d] - s1;
        dfs(d + 1,
            b1 + s1, 
            b2 + s2,
            c1 + (s1 &gt; 0), 
            c2 + (s2 &gt; 0), 
            p1 * fact[s1], 
            p2 * fact[s2]);
      }
    };
    dfs(0, 0, 0, 0, 0, 1.0, 1.0);
    return valid / total;
  }
};</pre>
</div></div>



<p>vector version</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  double getProbability(vector&lt;int&gt;&amp; balls) {
    const int k = balls.size();                    
    const int n = accumulate(begin(balls), end(balls), 0);
    vector&lt;double&gt; fact(49, 1.0);
    for (int i = 1; i &lt; fact.size(); ++i)
      fact[i] = fact[i - 1] * i;
    auto perms = [&amp;](const vector&lt;int&gt;&amp; bs, int n) -&gt; double {
      double p = fact[n];
      for (int b : bs) p /= fact[b];        
      return p;
    };
    vector&lt;int&gt; box1, box2;
    function&lt;double(int)&gt; dfs = [&amp;](int d) -&gt; double {
      const int n1 = accumulate(begin(box1), end(box1), 0);
      const int n2 = accumulate(begin(box2), end(box2), 0);
      if (n1 &gt; n / 2 || n2 &gt; n / 2) return 0;
      if (d == k)
        return (box1.size() == box2.size()) * perms(box1, n1) * perms(box2, n2);
      double total = 0;
      for (int s1 = 0; s1 &lt;= balls[d]; ++s1) {
        const int s2 = balls[d] - s1;
        if (s1) box1.push_back(s1);
        if (s2) box2.push_back(s2);
        total += dfs(d + 1);
        if (s1) box1.pop_back();
        if (s2) box2.pop_back();
      }
      return total;
    };
    return dfs(0) / perms(balls, n);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/">花花酱 LeetCode 1467. Probability of a Two Boxes Having The Same Number of Distinct Balls</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-1467-probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1359. Count All Valid Pickup and Delivery Options</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1359-count-all-valid-pickup-and-delivery-options/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1359-count-all-valid-pickup-and-delivery-options/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 23 Feb 2020 08:59:42 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[permutation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6364</guid>

					<description><![CDATA[<p>Given&#160;n&#160;orders, each order consist in pickup and delivery services.&#160; Count all valid pickup/delivery possible sequences such that delivery(i) is always after of&#160;pickup(i).&#160; Since the answer&#160;may&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1359-count-all-valid-pickup-and-delivery-options/">花花酱 LeetCode 1359. Count All Valid Pickup and Delivery Options</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&nbsp;<code>n</code>&nbsp;orders, each order consist in pickup and delivery services.&nbsp;</p>



<p>Count all valid pickup/delivery possible sequences such that delivery(i) is always after of&nbsp;pickup(i).&nbsp;</p>



<p>Since the answer&nbsp;may be too large,&nbsp;return it modulo&nbsp;10^9 + 7.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2
<strong>Output:</strong> 6
<strong>Explanation:</strong> All possible orders: 
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3
<strong>Output:</strong> 90
</pre>



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



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



<p>Solution: Combination</p>



<p>Let dp[i] denote the number of valid sequence of i nodes.<br><br>For i-1 nodes, the sequence length is 2(i-1).<br>For the i-th nodes,<br>If we put Pi at index = 0, then we can put Di at 1, 2, &#8230;, 2i &#8211; 2 =&gt; 2i-1 options.<br>If we put Pi at index = 1, then we can put Di at 2,3,&#8230;, 2i &#8211; 2 =&gt; 2i &#8211; 2 options.<br>&#8230;<br>If we put Pi at index = 2i-1, then we can put Di at 2i &#8211; 1=&gt; 1 option.<br>There are total (2i &#8211; 1 + 1) / 2 * (2i &#8211; 1) = i * (2*i &#8211; 1) options</p>



<p>dp[i] = dp[i &#8211; 1] * i * (2*i &#8211; 1)</p>



<p>or</p>



<p>dp[i] = 2n! / 2^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 countOrders(int n) {
    constexpr int kMod = 1e9 + 7;
    long ans = 1;
    for (int i = 2; i &lt;= n; ++i)
      ans = ans * i * (2 * i - 1) % kMod;      
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1359-count-all-valid-pickup-and-delivery-options/">花花酱 LeetCode 1359. Count All Valid Pickup and Delivery Options</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-1359-count-all-valid-pickup-and-delivery-options/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 46. Permutations</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-46-permutations/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-46-permutations/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 02 Oct 2019 16:28:32 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5702</guid>

					<description><![CDATA[<p>Given a collection of&#160;distinct&#160;integers, return all possible permutations. Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] Solution: DFS Time complexity: O(n!)Space&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-46-permutations/">花花酱 LeetCode 46. Permutations</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 collection of&nbsp;<strong>distinct</strong>&nbsp;integers, return all possible permutations.</p>



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



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



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



<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:
  vector&lt;vector&lt;int&gt;&gt; permute(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;vector&lt;int&gt;&gt; ans;
    vector&lt;int&gt; used(n);
    vector&lt;int&gt; path;
    function&lt;void(int)&gt; dfs = [&amp;](int d) {
      if (d == n) {
        ans.push_back(path);
        return;
      }
      for (int i = 0; i &lt; n; ++i) {
        if (used[i]) continue;
        used[i] = 1;
        path.push_back(nums[i]);
        dfs(d + 1);
        path.pop_back();
        used[i] = 0;
      }
    };
    dfs(0);
    return ans;
  }
};</pre>
</div></div>



<h2>Related Problems</h2>



<ul><li><a href="https://zxi.mytechroad.com/blog/searching/leetcode-47-permutations-ii/">https://zxi.mytechroad.com/blog/searching/leetcode-47-permutations-ii/</a></li></ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-46-permutations/">花花酱 LeetCode 46. Permutations</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-46-permutations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 60. Permutation Sequence</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-60-permutation-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-60-permutation-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 30 Sep 2019 03:22:42 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[fatorial]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5610</guid>

					<description><![CDATA[<p>The set&#160;[1,2,3,...,n]&#160;contains a total of&#160;n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for&#160;n&#160;= 3: "123"&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-60-permutation-sequence/">花花酱 LeetCode 60. Permutation 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>The set&nbsp;<code>[1,2,3,...,<em>n</em>]</code>&nbsp;contains a total of&nbsp;<em>n</em>! unique permutations.</p>



<p>By listing and labeling all of the permutations in order, we get the following sequence for&nbsp;<em>n</em>&nbsp;= 3:</p>



<ol><li><code>"123"</code></li><li><code>"132"</code></li><li><code>"213"</code></li><li><code>"231"</code></li><li><code>"312"</code></li><li><code>"321"</code></li></ol>



<p>Given&nbsp;<em>n</em>&nbsp;and&nbsp;<em>k</em>, return the&nbsp;<em>k</em><sup>th</sup>&nbsp;permutation sequence.</p>



<p><strong>Note:</strong></p>



<ul><li>Given&nbsp;<em>n</em>&nbsp;will be between 1 and 9 inclusive.</li><li>Given&nbsp;<em>k</em>&nbsp;will be between 1 and&nbsp;<em>n</em>! inclusive.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 3, k = 3
<strong>Output:</strong> "213"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 4, k = 9
<strong>Output:</strong> "2314"</pre>



<h2><strong>Solution: Math</strong></h2>



<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:
  string getPermutation(int n, int k) {
    vector&lt;int&gt; num;
    vector&lt;int&gt; fact(10, 1);
    for (int i = 1; i &lt;= 9; i++) {
      num.push_back(i);
      fact[i] = fact[i - 1] * i;
    }

    string s;
    k--;
    while (n--) {
      int d = k / fact[n];
      k %= fact[n];
      s += ('0' + num[d]);
      for (int i = d + 1; i &lt;= 9; i++)
        num[i - 1] = num[i];
    }
    return s;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-60-permutation-sequence/">花花酱 LeetCode 60. Permutation 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/math/leetcode-60-permutation-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1175. Prime Arrangements</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Sep 2019 05:10:02 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[prime]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5511</guid>

					<description><![CDATA[<p>Return the number of permutations of 1 to&#160;n&#160;so that prime numbers are at prime indices (1-indexed.) (Recall that an integer&#160;is prime if and only if&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/">花花酱 LeetCode 1175. Prime Arrangements</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>Return the number of permutations of 1 to&nbsp;<code>n</code>&nbsp;so that prime numbers are at prime indices (1-indexed.)</p>



<p><em>(Recall that an integer&nbsp;is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers&nbsp;both smaller than it.)</em></p>



<p>Since the answer may be large, return the answer&nbsp;<strong>modulo&nbsp;<code>10^9 + 7</code></strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5
<strong>Output:</strong> 12
<strong>Explanation:</strong> For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 100
<strong>Output:</strong> 682289015
</pre>



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



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



<h2><strong>Solution: Permutation</strong></h2>



<p>Count the number of primes in range [1, n], assuming there are p primes and n &#8211; p non-primes, we can permute each group separately. <br>ans = p!  * (n &#8211; p)!</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int numPrimeArrangements(int n) {
    const int kMod = 1e9 + 7;
    int p = 0;
    for (int i = 1; i &lt;= n; ++i)
      p += isPrime(i);
    long ans = 1;
    for (int i = 1; i &lt;= p; ++i)
      ans = (ans * i) % kMod;
    for (int i = 1; i &lt;= n - p; ++i)
      ans = (ans * i) % kMod;
    return ans;
  }
private:
  bool isPrime(int x) {
    if (x &lt; 2) return false;
    if (x == 2) return true;
    for (int i = 2; i &lt;= sqrt(x); ++i)
      if (x % i == 0) return false;
    return true;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1175-prime-arrangements/">花花酱 LeetCode 1175. Prime Arrangements</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/math/leetcode-1175-prime-arrangements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 31. Next Permutation</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 03 Oct 2018 02:28:58 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[in place]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4146</guid>

					<description><![CDATA[<p>Problem Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/">花花酱 LeetCode 31. Next Permutation</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Implement <strong>next permutation</strong>, which rearranges numbers into the lexicographically next greater permutation of numbers.</p>
<p>If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).</p>
<p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank" rel="noopener">in-place</a></strong> and use only constant extra memory.</p>
<p>Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.</p>
<p><code>1,2,3</code> → <code>1,3,2</code><br />
<code>3,2,1</code> → <code>1,2,3</code><br />
<code>1,1,5</code> → <code>1,5,1</code></p>
<h1><strong>Solution</strong></h1>
<p>Find the last acceding element x, swap with the smallest number y, y is after x that and y is greater than x.</p>
<p>Reverse the elements after x.</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 8 ms
class Solution {
public:
  void nextPermutation(vector&lt;int&gt;&amp; nums) {
    int i = nums.size() - 2;
    while (i &gt;= 0 &amp;&amp; nums[i + 1] &lt;= nums[i]) --i;
    if (i &gt;= 0) {
      int j = nums.size() - 1;
      while (j &gt;= 0 &amp;&amp; nums[j] &lt;= nums[i]) --j;
      swap(nums[i], nums[j]);
    }
    reverse(begin(nums) + i + 1, end(nums));
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, 48 ms
class Solution:
  def nextPermutation(self, nums):
    n = len(nums)
    i = n - 2
    while i &gt;= 0 and nums[i] &gt;= nums[i + 1]: i -= 1
    if i &gt;= 0:
      j = n - 1
      while j &gt;= 0 and nums[j] &lt;= nums[i]: j -= 1
      nums[i], nums[j] = nums[j], nums[i]
    nums[i + 1:] = nums[i+1:][::-1]</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-31-next-permutation/">花花酱 LeetCode 31. Next Permutation</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/algorithms/array/leetcode-31-next-permutation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 47. Permutations II</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-47-permutations-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-47-permutations-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 26 Jul 2018 15:17:47 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[deduplication]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3307</guid>

					<description><![CDATA[<p>Problem Given a collection of numbers that might contain duplicates, return all possible unique permutations. Example: Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ] Solution&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-47-permutations-ii/">花花酱 LeetCode 47. Permutations II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1>Problem</h1>
<p>Given a collection of numbers that might contain duplicates, return all possible unique permutations.</p>
<p><strong>Example:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> [1,1,2]
<strong>Output:</strong>
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]</pre>
<h1><strong>Solution</strong></h1>
<p>Time complexity: O(n!)</p>
<p>Space complexity: O(n + k)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 20 ms
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; permuteUnique(vector&lt;int&gt;&amp; nums) {
    sort(begin(nums), end(nums));
    vector&lt;vector&lt;int&gt;&gt; ans;
    vector&lt;int&gt; used(nums.size());
    vector&lt;int&gt; cur;
    dfs(nums, cur, used, ans);
    return ans;
  }
private:
  void dfs(const vector&lt;int&gt;&amp; nums, vector&lt;int&gt;&amp; cur, vector&lt;int&gt;&amp; used, vector&lt;vector&lt;int&gt;&gt;&amp; ans) {
    if (cur.size() == nums.size()) {
      ans.push_back(cur);
      return;
    }
    for (int i = 0; i &lt; nums.size(); ++i) {
      if (used[i]) continue;
      // Same number can be only used once at each depth.
      if (i &gt; 0 &amp;&amp; nums[i] == nums[i - 1] &amp;&amp; !used[i - 1]) continue;
      used[i] = 1;
      cur.push_back(nums[i]);
      dfs(nums, cur, used, ans);
      cur.pop_back();
      used[i] = 0;
    }
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/searching/leetcode-784-letter-case-permutation/">花花酱 LeetCode 784. Letter Case Permutation</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-47-permutations-ii/">花花酱 LeetCode 47. Permutations II</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-47-permutations-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 357. Count Numbers with Unique Digits</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-357-count-numbers-with-unique-digits/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-357-count-numbers-with-unique-digits/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 16 Jul 2018 15:14:53 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[production]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3196</guid>

					<description><![CDATA[<p>Problem Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x &#60; 10n. Example: Given n = 2, return 91. (The&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-357-count-numbers-with-unique-digits/">花花酱 LeetCode 357. Count Numbers with Unique Digits</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a <b>non-negative</b> integer n, count all numbers with unique digits, x, where 0 ≤ x &lt; 10<sup>n</sup>.</p>
<p><b>Example:</b><br />
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x &lt; 100, excluding <code>[11,22,33,44,55,66,77,88,99]</code>)</p>
<h1><strong>Solution: Math</strong></h1>
<p>f(0) = 1 (0)</p>
<p>f(1) = 10 (0 &#8211; 9)</p>
<p>f(2) = 9 * 9 (1-9 * (0 ~ 9 exclude the one from first digit))</p>
<p>f(3) = 9 * 9 * 8</p>
<p>f(4) = 9 * 9 * 8 * 7</p>
<p>&#8230;</p>
<p>f(x) = 0 if x &gt;= 10</p>
<p>ans = sum(f[1] ~ f[n])</p>
<p>Time complexity: O(1)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 0 ms
class Solution {
public:
  int countNumbersWithUniqueDigits(int n) {
    if (n == 0) return 1;
    vector&lt;int&gt; f(11);    
    f[1] = 10;
    f[2] = 9 * 9;
    for (int i = 3; i &lt;= 10; ++i)
      f[i] = f[i - 1] * (10 - i + 1);
    int ans = 0;
    for (int i = 0; i &lt;= min(10, n); ++i)
      ans += f[i];
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-357-count-numbers-with-unique-digits/">花花酱 LeetCode 357. Count Numbers with Unique Digits</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/math/leetcode-357-count-numbers-with-unique-digits/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 384. Shuffle an Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-384-shuffle-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-384-shuffle-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 16 Mar 2018 10:36:19 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[randomization]]></category>
		<category><![CDATA[shuffle]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2131</guid>

					<description><![CDATA[<p>Shuffle a set of numbers without duplicates. Example: [crayon-663c918700c42951094647/] C++ [crayon-663c918700c44028794843/] &#160;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-384-shuffle-an-array/">花花酱 LeetCode 384. Shuffle an Array</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>Shuffle a set of numbers without duplicates.</p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">// Init an array with set 1, 2, and 3.
int[] nums = {1,2,3};
Solution solution = new Solution(nums);

// Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned.
solution.shuffle();

// Resets the array back to its original configuration [1,2,3].
solution.reset();

// Returns the random shuffling of array [1,2,3].
solution.shuffle();</pre><p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 249 ms
class Solution {
public:
  Solution(vector&lt;int&gt; nums) {
    nums_ = std::move(nums);
  }

  /** Resets the array to its original configuration and return it. */
  vector&lt;int&gt; reset() {
    return nums_;
  }

  /** Returns a random shuffling of the array. */
  vector&lt;int&gt; shuffle() {
    vector&lt;int&gt; output(nums_);
    const int n = nums_.size();
    for (int i = 0; i &lt; n - 1; ++i) {      
      int j = rand() % (n - i) + i;
      std::swap(output[i], output[j]);
    }
    return output;
  }
private:
  vector&lt;int&gt; nums_;
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-384-shuffle-an-array/">花花酱 LeetCode 384. Shuffle an Array</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/algorithms/array/leetcode-384-shuffle-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
