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 <= 201 <= nums[i], k <= 1000This approach involves using an explicit stack to simulate recursion. We push tasks onto the stack as we go, allowing us to backtrack and manage different states or subproblems efficiently.
This C solution uses an iterative approach with a stack to keep track of tasks.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(n)
This approach is based on solving subproblems recursively, caching the results of completed subproblems, to avoid redundant calculations, greatly improving efficiency.
This C solution uses recursion with memoization to cache results of subproblems.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), Space Complexity: O(n)
| Approach | Complexity |
|---|---|
| Approach 1: Iterative Solution using a Stack | Time Complexity: O(n), Space Complexity: O(n) |
| Approach 2: Recursive Solution with Memoization | Time Complexity: O(n), Space Complexity: O(n) |
The Number of Beautiful Subsets - Leetcode 2597 - Python • NeetCodeIO • 12,544 views views
Watch 9 more video solutions →Practice The Number of Beautiful Subsets with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor