Skip to content

Latest commit

 

History

History
 
 

2597

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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 <= 20
  • 1 <= nums[i], k <= 1000

Related Topics:
Array, Dynamic Programming, Backtracking

Similar Questions:

Solution 1. Backtracking

The brute force way is to generate 2^N-1 non-empty subsets using DFS, and check each one of them are valid, taking O(2^N * N) time.

There are lots of unnecessary checks. For example, if the subset already contains conflicts, all the subsequently generated subsets won't be valid.

So, we can use backtracking to skip those cases.

// OJ: https://leetcode.com/problems/the-number-of-beautiful-subsets
// Author: github.com/lzl124631x
// Time: O(2^N)
// Space: O(N)
class Solution {
public:
    int beautifulSubsets(vector<int>& A, int k) {
        int ans = 0, cnt[1001] = {}, used[1001] = {}, i = 0;
        for (int i : A) cnt[i]++;
        sort(begin(A), end(A));
        auto last = unique(begin(A), end(A));
        A.erase(last, end(A));
        function<void(int,int)> dfs = [&](int i, int c) {
            if (i == A.size()) {
                ans += c; 
                return;
            }
            if (A[i] - k <= 0 || !used[A[i] - k]) { // use A[i]
                used[A[i]] = 1;
                dfs(i + 1, c * ((1 << cnt[A[i]]) - 1));
                used[A[i]] = 0;
            }
            dfs(i + 1, c); // don't use A[i]
        };
        dfs(0, 1);
        return ans - 1;
    }
};