<p>You are given an array <code>nums</code> of positive integers and a <strong>positive</strong> integer <code>k</code>.</p>

<p>A subset of <code>nums</code> is <strong>beautiful</strong> if it does not contain two integers with an absolute difference equal to <code>k</code>.</p>

<p>Return <em>the number of <strong>non-empty beautiful </strong>subsets of the array</em> <code>nums</code>.</p>

<p>A <strong>subset</strong> of <code>nums</code> is an array that can be obtained by deleting some (possibly none) elements from <code>nums</code>. Two subsets are different if and only if the chosen indices to delete are different.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,4,6], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The beautiful subsets of the array nums are: [2], [4], [6], [2, 6].
It can be proved that there are only 4 beautiful subsets in the array [2,4,6].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The beautiful subset of the array nums is [1].
It can be proved that there is only 1 beautiful subset in the array [1].
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 20</code></li>
	<li><code>1 &lt;= nums[i], k &lt;= 1000</code></li>
</ul>

// Tag: Backtracking

// Create Date: 2024/5/23
// Review Date: [2024/5/30, 2024/6/25]

#include <bits/stdc++.h>  
using namespace std;

// O(2^n)Time, O(n)Space, 因为potentially需要generate all subsets
class Solution {
public:
    void backtracking(const vector<int>& nums, const int k,
                      const int idx, unordered_map<int, int>& um, int& ans)
    {
        if (!um.empty())
        {
            ++ans;
        }

        for (int i = idx; i < nums.size(); ++i)
        {
            const int a = nums[i] + k;
            const int b = nums[i] - k;
            if (um.find(a) == um.end() && um.find(b) == um.end())
            {
                // !!! 必须用um而不是unordered_set，否则此时的call有可能erase掉之前的，
                // which is the case if there is any duplicate
                ++um[nums[i]];
                backtracking(nums, k, i + 1, um, ans);

                if (um[nums[i]] == 1)
                {
                    um.erase(nums[i]);
                }
                else
                {
                    --um[nums[i]];
                }
            }
        }
    }

    int beautifulSubsets(vector<int>& nums, int k) {
        // unordered_set<int> us;
        unordered_map<int, int> um;
        int ans = 0;
        backtracking(nums, k, 0, um, ans);

        return ans;
    }
};
130717