Problem Description
Given an array of positive integers nums and a positive integer k, count the number of non-empty subsets of nums (where subsets are defined by chosen indices, even if numbers are repeated) which are considered beautiful. A subset is beautiful if it does not contain any two integers whose absolute difference equals k.
Key Insights
- Since the maximum length of nums is 18, it is feasible to try all 2^n non-empty subsets.
- When checking a subset, ensure no two elements have a difference equal to k.
- For each subset, converting the chosen elements into a set (or sorting) enables efficient pair checks.
- Brute-force bitmask enumeration or depth-first/backtracking can be used, given the small input size.
Space and Time Complexity
Time Complexity: O(2^n * n), where n is the size of nums (n ≤ 18). Space Complexity: O(n) for generating each subset.
Solution
We use bitmask enumeration to evaluate all possible non-empty subsets. For each bitmask:
- Generate the subset by selecting elements corresponding to set bits.
- Check if the subset is beautiful by ensuring that for every element v in the subset, v+k does not exist (this avoids having any pair with an absolute difference equal to k).
- Count the beautiful subsets and return the count.
The trick here is to leverage bit masks to represent subsets and use a set (or sorting) to check conflicts in O(n) time per subset. Given the small constraint (n ≤ 18), the approach is efficient and straightforward.