The Number of Beautiful Subsets Problem
Description
LeetCode Problem 2597.
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 <= 181 <= nums[i], k <= 1000
Solution
Approach: Counting + Backtracking
Keep an array cnt with the count of each number chosen so far, and a counter ans that starts at -1 so that the empty subset is not counted.
For each number x, in order, there are two choices:
- Skip
xand move on to the next number. - Take
x, which is allowed only if neitherx + knorx - khas been chosen. Increasecnt[x], recurse, then undo the change.
Every time the recursion passes the end of the array, a beautiful subset has been built, so ans is incremented.
Complexity: time O(2^n), space O(n) for the recursion (plus the count array), where n is the length of nums.
from collections import Counter
class Solution:
def beautifulSubsets(self, nums: List[int], k: int) -> int:
def dfs(i: int) -> None:
nonlocal ans
if i >= len(nums):
ans += 1
return
dfs(i + 1)
if cnt[nums[i] + k] == 0 and cnt[nums[i] - k] == 0:
cnt[nums[i]] += 1
dfs(i + 1)
cnt[nums[i]] -= 1
ans = -1
cnt = Counter()
dfs(0)
return ans