Skip to content

Commit d9d848a

Browse files
authored
Create number-of-ways-to-wear-different-hats-to-each-other.cpp
1 parent 1f9ce1c commit d9d848a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time: O(h * 2^n)
2+
// Space: O(2^n)
3+
4+
class Solution {
5+
public:
6+
int numberWays(vector<vector<int>>& hats) {
7+
static const int MOD = 1e9 + 7;
8+
static const int HAT_SIZE = 40;
9+
10+
vector<vector<int>> hat_to_people(HAT_SIZE);
11+
for (int i = 0; i < hats.size(); ++i) {
12+
for (const auto& hat: hats[i]) {
13+
hat_to_people[hat - 1].emplace_back(i);
14+
}
15+
}
16+
vector<int> dp(1 << hats.size());
17+
dp[0] = 1;
18+
for (const auto& people : hat_to_people) {
19+
for (int mask = dp.size() - 1; mask >= 0; --mask) {
20+
for (const int& p: people) {
21+
if (mask & (1 << p)) {
22+
continue;
23+
}
24+
dp[mask | (1 << p)] += dp[mask];
25+
dp[mask | (1 << p)] %= MOD;
26+
}
27+
}
28+
}
29+
return dp.back();
30+
}
31+
};

0 commit comments

Comments
 (0)