[LeetCode] The Number of Beautiful Subsets

2597. The Number of Beautiful Subsets

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
int dp[22];
public:
int beautifulSubsets(vector<int>& A, int k) {
unordered_map<int, vector<int>> mp;
for(auto a : A) mp[a%k].push_back(a);
dp[0] = 1, dp[1] = 2;
for(int i = 2; i < 22; i++) dp[i] = dp[i-1] + dp[i-2];
int res = 1;
for(auto [_,vec] : mp) {
if(vec.size() == 1) res = res * 2;
else {
sort(begin(vec), end(vec));
vector<int> now{vec[0]};
for(int i = 1; i < vec.size(); i++) {
if(now.back() + k == vec[i]) now.push_back(vec[i]);
else {
res *= dp[now.size()];
now = {vec[i]};
}
}
res *= dp[now.size()];
}
}
return res - 1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int beautifulSubsets(vector<int>& A, int k) {
int res = 0, n = A.size();
sort(begin(A), end(A));
unordered_set<int> bad;
for(int i = 1; i < (1<<n); i++) {
if(bad.count(i)) {
for(int j = 0; j < n; j++) {
if(i & (1<<j)) continue;
bad.insert(i ^ (1<<j));
}
continue;
}
bool ok = true;
unordered_set<int> us;
for(int j = 0; j < n and ok; j++) {
if(i & (1<<j)) {
if(us.count(A[j] - k)) ok = false;
us.insert(A[j]);
}
}
if(!ok) {
for(int j = 0; j < n; j++) {
if(i & (1<<j)) continue;
bad.insert(i ^ (1<<j));
}
}
if(ok) res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/03/19/PS/LeetCode/the-number-of-beautiful-subsets/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.