Skip to content

Commit 4fedf13

Browse files
authored
Update 1434-number-of-ways-to-wear-different-hats-to-each-other.js
1 parent b0e6b74 commit 4fedf13

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

1434-number-of-ways-to-wear-different-hats-to-each-other.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,46 @@
1+
/**
2+
* @param {number[][]} hats
3+
* @return {number}
4+
*/
5+
const numberWays = function(hats) {
6+
const map = new Map()
7+
const n = hats.length
8+
for(let i = 0; i < n; i++) {
9+
for(const h of hats[i]) {
10+
if(!map.has(h)) map.set(h, [])
11+
map.get(h).push(i)
12+
}
13+
}
14+
const mod = 1e9 + 7
15+
const allMask = (1 << n) - 1
16+
const dp = Array.from({ length: 41 }, () => Array(1024))
17+
18+
return dfs(1, 0)
19+
20+
function dfs(hat, mask) {
21+
if(mask === allMask) return 1
22+
if(hat > 40) return 0
23+
if(dp[hat][mask] != null) return dp[hat][mask]
24+
25+
let res = 0
26+
27+
// not using this `hat`
28+
res += dfs(hat + 1, mask)
29+
for(const p of (map.get(hat) || [])) {
30+
if(((mask >> p) & 1) === 0) {
31+
res += dfs(hat + 1, mask | (1 << p))
32+
res = res % mod
33+
}
34+
}
35+
dp[hat][mask] = res
36+
return res
37+
}
38+
39+
};
40+
41+
// another
42+
43+
144
/**
245
* @param {number[][]} hats
346
* @return {number}

0 commit comments

Comments
 (0)