We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1f9ce1c commit d9d848aCopy full SHA for d9d848a
C++/number-of-ways-to-wear-different-hats-to-each-other.cpp
@@ -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