1
from functools import cache5
def numberWays(self, hats: List[List[int]]) -> int:8
temp = [[] for _ in range(40)]9
for i, person in enumerate(hats):11
temp[hat - 1].append(i)14
# drop empty hats and sort15
hats = [h for h in hats if h]16
hats.sort(key=lambda h: len(h))20
full = 2**n_persons - 121
bits = [1 << i for i in range(n_persons)]25
def get_count(i, has_hat):27
# all persons have a hat34
for person in hats[i]:36
# still not have a hat?37
if has_hat & bits[person] == 0:38
# the person wears i-th hat39
result += get_count(i + 1, has_hat | bits[person])40
# no one wears i-th hat41
result += get_count(i + 1, has_hat)43
# return modulo (10 ** 9 - 7)46
# start form 0-th hat and47
# no person wearing a hat48
return get_count(0, 0)