File tree 2 files changed +55
-1
lines changed
2 files changed +55
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,301 LeetCode solutions in JavaScript
1
+ # 1,302 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1094
1094
1431|[ Kids With the Greatest Number of Candies] ( ./solutions/1431-kids-with-the-greatest-number-of-candies.js ) |Easy|
1095
1095
1432|[ Max Difference You Can Get From Changing an Integer] ( ./solutions/1432-max-difference-you-can-get-from-changing-an-integer.js ) |Medium|
1096
1096
1433|[ Check If a String Can Break Another String] ( ./solutions/1433-check-if-a-string-can-break-another-string.js ) |Medium|
1097
+ 1434|[ Number of Ways to Wear Different Hats to Each Other] ( ./solutions/1434-number-of-ways-to-wear-different-hats-to-each-other.js ) |Hard|
1097
1098
1436|[ Destination City] ( ./solutions/1436-destination-city.js ) |Easy|
1098
1099
1437|[ Check If All 1's Are at Least Length K Places Away] ( ./solutions/1437-check-if-all-1s-are-at-least-length-k-places-away.js ) |Easy|
1099
1100
1443|[ Minimum Time to Collect All Apples in a Tree] ( ./solutions/1443-minimum-time-to-collect-all-apples-in-a-tree.js ) |Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1434. Number of Ways to Wear Different Hats to Each Other
3
+ * https://leetcode.com/problems/number-of-ways-to-wear-different-hats-to-each-other/
4
+ * Difficulty: Hard
5
+ *
6
+ * There are n people and 40 types of hats labeled from 1 to 40.
7
+ *
8
+ * Given a 2D integer array hats, where hats[i] is a list of all hats preferred by the ith person.
9
+ *
10
+ * Return the number of ways that n people can wear different hats from each other.
11
+ *
12
+ * Since the answer may be too large, return it modulo 109 + 7.
13
+ */
14
+
15
+ /**
16
+ * @param {number[][] } hats
17
+ * @return {number }
18
+ */
19
+ var numberWays = function ( hats ) {
20
+ const MOD = 1e9 + 7 ;
21
+ const hatToPeople = Array ( 41 ) . fill ( ) . map ( ( ) => [ ] ) ;
22
+ const cache = new Map ( ) ;
23
+
24
+ for ( let person = 0 ; person < hats . length ; person ++ ) {
25
+ for ( const hat of hats [ person ] ) {
26
+ hatToPeople [ hat ] . push ( person ) ;
27
+ }
28
+ }
29
+
30
+ function assignHats ( hat , usedMask ) {
31
+ if ( hat > 40 ) {
32
+ return usedMask === ( 1 << hats . length ) - 1 ? 1 : 0 ;
33
+ }
34
+
35
+ const key = `${ hat } :${ usedMask } ` ;
36
+ if ( cache . has ( key ) ) {
37
+ return cache . get ( key ) ;
38
+ }
39
+
40
+ let ways = assignHats ( hat + 1 , usedMask ) ;
41
+
42
+ for ( const person of hatToPeople [ hat ] ) {
43
+ if ( ! ( usedMask & ( 1 << person ) ) ) {
44
+ ways = ( ways + assignHats ( hat + 1 , usedMask | ( 1 << person ) ) ) % MOD ;
45
+ }
46
+ }
47
+
48
+ cache . set ( key , ways ) ;
49
+ return ways ;
50
+ }
51
+
52
+ return assignHats ( 1 , 0 ) ;
53
+ } ;
You can’t perform that action at this time.
0 commit comments