-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2597.TheNumberOfBeautifulSubsets.cpp
More file actions
64 lines (54 loc) · 1.34 KB
/
2597.TheNumberOfBeautifulSubsets.cpp
File metadata and controls
64 lines (54 loc) · 1.34 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public:
vector<int>* m_nums;
int m_n, m_k;
unordered_map<int, int> m_workingSet;
int m_totalSubsets;
void calculateSubsets(const int offset) {
if (offset >= m_n) {
// Count set as beautiful.
if (!m_workingSet.empty()) m_totalSubsets++;
// End of the line, pal.
return;
}
// Process non-derived subsets.
calculateSubsets(offset + 1);
// Get key value.
const int key = (*m_nums)[offset];
// Check if beautiful.
if (m_workingSet.find(key + m_k) != m_workingSet.end() ||
m_workingSet.find(key - m_k) != m_workingSet.end()) {
// Not beautiful.
return;
}
// Update working set.
auto it = m_workingSet.find(key);
if (it == m_workingSet.end()) {
// Add to working set.
it = m_workingSet.emplace(key, 1).first;
} else {
// Update working set count.
it->second++;
}
// Calculate derived subsets.
calculateSubsets(offset + 1);
// Update working set count.
if (--it->second <= 0)
// Remove from working set.
m_workingSet.erase(it);
}
int beautifulSubsets(vector<int>& nums, int k) {
// Speed thingies.
// ios_base::sync_with_stdio(false);
// cin.tie(nullptr);
// cout.tie(nullptr);
// Calculation variables.
m_k = k;
m_nums = &nums;
m_n = m_nums->size();
m_totalSubsets = 0;
// Calculate total subsets.
calculateSubsets(0);
return m_totalSubsets;
}
};