Number of Ways to Wear Different Hats to Each Other Problem
Description
LeetCode Problem 1434.
There are n people and 40 types of hats labeled from 1 to 40.
Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the i^th person.
Return the number of ways that n people can wear different hats from each other.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: hats = [[3,4],[4,5],[5]]
Output: 1
Explanation: There is only one way to choose hats given the conditions.
First person chooses hat 3, Second person chooses hat 4 and last one hat 5.
Example 2:
Input: hats = [[3,5,1],[3,5]]
Output: 4
Explanation: There are 4 ways to choose hats:
(3,5), (5,3), (1,3) and (1,5)
Example 3:
Input: hats = [[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
Output: 24
Explanation: Each person can choose hats labeled from 1 to 4.
Number of Permutations of (1,2,3,4) = 24.
Constraints:
n == hats.length1 <= n <= 101 <= hats[i].length <= 401 <= hats[i][j] <= 40hats[i]contains a list of unique integers.
Solution
Approach: Bitmask DP over Hats
Assigning hats person by person would need to remember which of the 40 hats are taken, which is 240 states. Turn it around: there are only n <= 10 people, so go hat by hat and remember which people already wear one, a bitmask with at most 210 = 1024 values.
Let f[mask] be the number of ways to give hats considered so far to exactly the people in mask, each person one different hat. Start with f[0] = 1. For each hat h from 1 to 40, either nobody wears it (the counts stay) or one person p who likes h and is in mask wears it:
new f[mask] = f[mask] + sum of f[mask without p] for each p in likes[h] with p in mask
To reuse one array, go through the masks from largest to smallest: mask without p is smaller than mask, so it still holds its value from before hat h. That makes sure one hat goes to at most one person. The answer is f[all people], modulo 109 + 7.
Complexity: O(40 · 2n · n) time, about 4 · 105 steps, and O(2n) extra space.
class Solution:
def numberWays(self, hats: List[List[int]]) -> int:
MOD = 10**9 + 7
n = len(hats)
likes = [[] for _ in range(41)] # likes[h]: the people who like hat h
for person, hs in enumerate(hats):
for h in hs:
likes[h].append(person)
# f[mask]: ways to give hats seen so far to exactly the people in mask
f = [0] * (1 << n)
f[0] = 1
for h in range(1, 41):
# go down so f[mask ^ bit] (a smaller mask) still holds the value before hat h
for mask in range((1 << n) - 1, 0, -1):
for person in likes[h]:
if mask >> person & 1:
f[mask] = (f[mask] + f[mask ^ (1 << person)]) % MOD
return f[(1 << n) - 1]