Approch 1 : Using Array
class Solution:
def beautifulSubsets(self, nums: List[int], k: int) -> int:
ans = 0
def checkBeauty(arr, num):
for e in arr:
if abs(e - num) == k:
return False
return True
def backtrack(index, temp):
nonlocal ans
if index >= len(nums):
ans += 1
return
if checkBeauty(temp, nums[index]):
backtrack(index + 1, temp + [nums[index]])
backtrack(index + 1, temp)
for index, e in enumerate(nums):
backtrack(index + 1, [nums[index]])
return ans
This approch would be useful if we were to get the actual values in subset but for this problem we just need count so we can use set for better retrival.
Approch 2 : Using Set
class Solution:
def beautifulSubsets(self, nums: List[int], k: int) -> int:
ans = 0
L = len(nums)
checkBeauty = lambda arr, num: (num + k) not in arr and (num - k) not in arr
def backtrack(index, temp):
nonlocal ans
if index >= L:
ans += 1
return
if checkBeauty(temp, nums[index]):
backtrack(index + 1, temp | {nums[index]})
backtrack(index + 1, temp)
for index, e in enumerate(nums):
backtrack(index + 1, {nums[index], nums[index]})
return ans
Here we don't worry about values, instead we collect unique values for the subset to check it's beauty ✌️