forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distribute-repeating-integers.cpp
47 lines (46 loc) · 1.81 KB
/
distribute-repeating-integers.cpp
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
// Time: O(n + m * 3^m)
// Space: O(n + 2^m)
class Solution {
public:
bool canDistribute(vector<int>& nums, vector<int>& quantity) {
unordered_map<int, int> count;
for(int i = 0; i < size(nums); ++i) {
++count[nums[i]];
}
int total = (1 << size(quantity)) - 1;
vector<int> requirement(total + 1);
for (int mask = 0; mask < size(requirement); ++mask) { // Time: O(2^m)
for (int i = 0; i < size(quantity); ++i) { // Time: O(m)
if (mask & (1 << i)) {
requirement[mask] += quantity[i];
}
}
}
vector<vector<int>> dp(2, vector<int>(total + 1));
dp[0][0] = 1;
int i = 0;
vector<int> cnts;
for (const auto& [_, cnt] : count) {
cnts.emplace_back(cnt);
}
if (size(quantity) < size(cnts)) { // at most use top m cnts
nth_element(begin(cnts), begin(cnts) + size(quantity) - 1, end(cnts), greater<int>());
cnts.resize(size(quantity));
}
for (int i = 0; i < size(cnts); ++i) { // Time: O(m)
dp[(i + 1) % 2] = vector<int>(total + 1);
// submask enumeration:
// => sum(nCr(m, k) * 2^k for k in xrange(m+1)) = (1 + 2)^m = 3^m
// => Time: O(3^m), see https://cp-algorithms.com/algebra/all-submasks.html
for (int mask = total; mask >= 0; --mask) {
dp[(i + 1) % 2][mask] |= dp[i % 2][mask];
for (int submask = mask; submask > 0; submask = (submask - 1) & mask) {
if (requirement[submask] <= cnts[i] && dp[i % 2][mask ^ submask]) {
dp[(i + 1) % 2][mask] = 1;
}
}
}
}
return dp[size(cnts) % 2][total];
}
};