The Number of Beautiful Subsets - 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,4,6], k = 2
›
Output:
4
💡 Note:
Beautiful subsets are [2], [4], [6], [2,6]. Note that [2,4] and [4,6] are not beautiful since |2-4|=2=k and |4-6|=2=k
Example 2 — Small Array
$
Input:
nums = [1], k = 1
›
Output:
1
💡 Note:
Only one subset [1] which is beautiful since it has only one element
Example 3 — No Valid Pairs
$
Input:
nums = [4,2,5,9,10,3], k = 1
›
Output:
23
💡 Note:
Many subsets are valid. Elements that differ by 1 cannot be together: (2,3), (4,5), (9,10)
Constraints
- 1 ≤ nums.length ≤ 20
- 1 ≤ nums[i], k ≤ 1000
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums=[2,4,6] and k=2 (forbidden difference)
2
Process
Generate all subsets and filter out those with |a-b|=k
3
Output
Count of beautiful subsets: 4
Key Takeaway
🎯 Key Insight: Use backtracking with early pruning to avoid exploring subsets that contain conflicting pairs
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code