2597. The Number of Beautiful Subsets
Description
You are given an array nums
of positive integers and a positive integer k
.
A subset of nums
is beautiful if it does not contain two integers with an absolute difference equal to k
.
Return the number of non-empty beautiful subsets of the array nums
.
A subset of nums
is an array that can be obtained by deleting some (possibly none) elements from nums
. Two subsets are different if and only if the chosen indices to delete are different.
Example 1:
Input: nums = [2,4,6], k = 2 Output: 4 Explanation: 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].
Example 2:
Input: nums = [1], k = 1 Output: 1 Explanation: The beautiful subset of the array nums is [1]. It can be proved that there is only 1 beautiful subset in the array [1].
Constraints:
1 <= nums.length <= 18
1 <= nums[i], k <= 1000
Solutions
Solution 1: Counting + Backtracking
We use a hash table or array \(\textit{cnt}\) to record the currently selected numbers and their counts, and use \(\textit{ans}\) to record the number of beautiful subsets. Initially, \(\textit{ans} = -1\) to exclude the empty set.
For each number \(x\) in the array \(\textit{nums}\), we have two choices:
- Do not select \(x\), and directly recurse to the next number;
- Select \(x\), and check if \(x + k\) and \(x - k\) have already appeared in \(\textit{cnt}\). If neither has appeared, we can select \(x\). In this case, we increment the count of \(x\) by one, recurse to the next number, and then decrement the count of \(x\) by one.
Finally, we return \(\textit{ans}\).
The time complexity is \(O(2^n)\), and the space complexity is \(O(n)\). Where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|