|
| 1 | +/** |
| 2 | + * 1494. Parallel Courses II |
| 3 | + * https://leetcode.com/problems/parallel-courses-ii/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are |
| 7 | + * also given an array relations where relations[i] = [prevCoursei, nextCoursei], representing a |
| 8 | + * prerequisite relationship between course prevCoursei and course nextCoursei: course prevCoursei |
| 9 | + * has to be taken before course nextCoursei. Also, you are given the integer k. |
| 10 | + * |
| 11 | + * In one semester, you can take at most k courses as long as you have taken all the prerequisites |
| 12 | + * in the previous semesters for the courses you are taking. |
| 13 | + * |
| 14 | + * Return the minimum number of semesters needed to take all courses. The testcases will be |
| 15 | + * generated such that it is possible to take every course. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} n |
| 20 | + * @param {number[][]} relations |
| 21 | + * @param {number} k |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var minNumberOfSemesters = function(n, relations, k) { |
| 25 | + const prerequisites = new Array(n).fill(0); |
| 26 | + for (const [prev, next] of relations) { |
| 27 | + prerequisites[next - 1] |= 1 << (prev - 1); |
| 28 | + } |
| 29 | + |
| 30 | + const cache = new Array(1 << n).fill(-1); |
| 31 | + |
| 32 | + return findMinSemesters(0); |
| 33 | + |
| 34 | + function findMinSemesters(courses) { |
| 35 | + if (courses === (1 << n) - 1) return 0; |
| 36 | + if (cache[courses] !== -1) return cache[courses]; |
| 37 | + |
| 38 | + let available = 0; |
| 39 | + for (let i = 0; i < n; i++) { |
| 40 | + if (!(courses & (1 << i)) && (courses & prerequisites[i]) === prerequisites[i]) { |
| 41 | + available |= 1 << i; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + let minSemesters = n + 1; |
| 46 | + const combinations = function(pos, count, selected) { |
| 47 | + if (count === 0 || pos === n) { |
| 48 | + if (selected) { |
| 49 | + minSemesters = Math.min( |
| 50 | + minSemesters, |
| 51 | + 1 + findMinSemesters(courses | selected) |
| 52 | + ); |
| 53 | + } |
| 54 | + return; |
| 55 | + } |
| 56 | + if (!(available & (1 << pos))) return combinations(pos + 1, count, selected); |
| 57 | + combinations(pos + 1, count - 1, selected | (1 << pos)); |
| 58 | + combinations(pos + 1, count, selected); |
| 59 | + }; |
| 60 | + |
| 61 | + combinations(0, Math.min(k, bitCount(available)), 0); |
| 62 | + cache[courses] = minSemesters; |
| 63 | + return minSemesters; |
| 64 | + } |
| 65 | + |
| 66 | + function bitCount(num) { |
| 67 | + let count = 0; |
| 68 | + while (num) { |
| 69 | + count += num & 1; |
| 70 | + num >>= 1; |
| 71 | + } |
| 72 | + return count; |
| 73 | + } |
| 74 | +}; |
0 commit comments