Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints
1 <= nums.length <= 20
1 <= nums[i], k <= 1000
Solution
Method 1 - Backtracking generating subsets
This solution is very similar to Subsets.
Here is the video explanation:
Code
|
|
Complexity
- ⏰ Time complexity:
O(n.2^n)
(O(n logn)
for sorting andO(2^n)
for dfs onn
elements) - 🧺 Space complexity:
O(n)
using recursive stacks
Method 2 - Backtracking but just focus on count
If we see in previous solution, we run contains
on the list, and instead we can use set or map to track the elements added in the list. And as the elements may repeat, we will use hashmap, and store the frequency of the elements added so far.
We also sort the array, so that we can check the difference easily.
Base Case
- If the current index
idx
reaches the end of the array, check if the subset formed is non-empty. If yes, return 1 (valid subset), otherwise return 0.
Backtracking
Now the algorithm stays simple. We include the element in the set, and get the count. We check it by using map.containsKey(nums[idx] - k)
, as the array is sorted (we don’t have to do map.containsKey(nums[idx] + k)
as nums[idx]+K
is not yet added.)
Code
|
|
Complexity
- ⏰ Time complexity:
O(n.2^n)
- 🧺 Space complexity:
O(n)