Skip to content

Commit a678a67

Browse files
authored
Update 1494-parallel-courses-ii.js
1 parent 1a42bc4 commit a678a67

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

1494-parallel-courses-ii.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,50 @@ function bitCount(n) {
4848
n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
4949
return (((n + (n >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24
5050
}
51+
52+
// another
53+
54+
/**
55+
* @param {number} n
56+
* @param {number[][]} dependencies
57+
* @param {number} k
58+
* @return {number}
59+
*/
60+
const minNumberOfSemesters = function (n, dependencies, k) {
61+
const pre = Array(n).fill(0)
62+
const limit = 1 << n
63+
for(const [p, v] of dependencies) {
64+
pre[v - 1] |= (1 << (p - 1))
65+
}
66+
const dp = Array(limit).fill(Infinity)
67+
dp[0] = 0
68+
69+
for(let learned = 0; learned < limit; learned++) {
70+
let wait = 0
71+
for(let i = 0; i < n; i++) {
72+
if( (learned & pre[i]) === pre[i]) {
73+
wait |= (1 << i)
74+
}
75+
}
76+
wait = wait & (~learned)
77+
for(let sub = wait; sub; sub = (sub - 1) & wait) {
78+
if(bitCnt(sub) > k) continue
79+
const mask = learned | sub
80+
dp[mask] = Math.min(dp[mask], dp[learned] + 1)
81+
}
82+
}
83+
84+
return dp[limit - 1]
85+
}
86+
87+
function bitCnt(num) {
88+
let res = 0
89+
while(num) {
90+
if(num & 1) res++
91+
num = num >> 1
92+
}
93+
94+
return res
95+
}
96+
97+

0 commit comments

Comments
 (0)