<p>You are given an integer <code>n</code>, which indicates that there are <code>n</code> courses labeled from <code>1</code> to <code>n</code>. You are also given an array <code>relations</code> where <code>relations[i] = [prevCourse<sub>i</sub>, nextCourse<sub>i</sub>]</code>, representing a prerequisite relationship between course <code>prevCourse<sub>i</sub></code> and course <code>nextCourse<sub>i</sub></code>: course <code>prevCourse<sub>i</sub></code> has to be taken before course <code>nextCourse<sub>i</sub></code>. Also, you are given the integer <code>k</code>.</p>

<p>In one semester, you can take <strong>at most</strong> <code>k</code> courses as long as you have taken all the prerequisites in the <strong>previous</strong> semesters for the courses you are taking.</p>

<p>Return <em>the <strong>minimum</strong> number of semesters needed to take all courses</em>. The testcases will be generated such that it is possible to take every course.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_1.png" style="width: 269px; height: 147px;" />
<pre>
<strong>Input:</strong> n = 4, relations = [[2,1],[3,1],[1,4]], k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/05/22/leetcode_parallel_courses_2.png" style="width: 271px; height: 211px;" />
<pre>
<strong>Input:</strong> n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2
<strong>Output:</strong> 4
<strong>Explanation:</strong> The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 15</code></li>
	<li><code>1 &lt;= k &lt;= n</code></li>
	<li><code>0 &lt;= relations.length &lt;= n * (n-1) / 2</code></li>
	<li><code>relations[i].length == 2</code></li>
	<li><code>1 &lt;= prevCourse<sub>i</sub>, nextCourse<sub>i</sub> &lt;= n</code></li>
	<li><code>prevCourse<sub>i</sub> != nextCourse<sub>i</sub></code></li>
	<li>All the pairs <code>[prevCourse<sub>i</sub>, nextCourse<sub>i</sub>]</code> are <strong>unique</strong>.</li>
	<li>The given graph is a directed acyclic graph.</li>
</ul>

class Solution:
    '''
    Data Structures

We need to know the layout of the graph, who points to what. Let's keep a structure like graph = {node: [children]}
We also need to encode the information of how may in-edges are there for each node. We store that in a list like: in_degrees = [values]. We keep the in_degrees and graph separate for implementation reasons.
Implementation detail: the inputs are 1 indexed, we make everything 0-indexed for easier implementations.

    Nodes
    There are two types of nodes:

    There are nodes which have been already considered. Let's label them with 0.
    There are nodes which have not been taken yet. Let's label them with 1.
    Note that even if a node is marked 1, it does not mean its in_degree[node] is 0. 
    It only means it needs to be taken - either in the present or in the future.

    Moreover, labelling a node either 0 or 1 allows us to represent the status 
    of the problem in a neat format. What we have done here is called bit masking. 
    mask = 10110 represents the nodes 1, 2, 4 are yet to be considered 
    (aka the course is yet to be taken), and the rest have already been taken.

    Recursion
    We know that decisions taken now can produce different results later on. This makes the recursive approach favourable. For each particular iteration, we consider all the possible combinations of the currently available nodes - in_degree[node] == 0 and mask & 1 << node. The second part is checking if the nodeth bit is set in mask.

    the key is which courses to take if there are more courses available than k, and it comes down to backtracking, combined with topo sort
    '''
    @lru_cache(None)
    def recurse(self, mask, in_degrees):
        # if all bits are 0, we have taken all courses
        if not mask:
            return 0

        # all the nodes that *can* be taken now, following both the properties
        nodes = [i for i in range(self.n) if mask & 1 << i and in_degrees[i] == 0]

        ans = float('inf')
        # enumerating all possible combinations
        for k_nodes in combinations(nodes, min(self.k, len(nodes))):
            new_mask, new_in_degrees = mask, list(in_degrees)

            # updating what would happen to new_mask and new_in_degress
            # if we considered the nodes in k_nodes
            for node in k_nodes:
                new_mask ^= 1 << node
                for child in self.graph[node]:
                    new_in_degrees[child] -= 1        

            # heart of recursion, note +1
            ans = min(ans, 1 + self.recurse(new_mask, tuple(new_in_degrees)))
        return ans

    def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:
        self.n = n
        self.k = k
        in_degrees = [0] * self.n
        self.graph = defaultdict(list)
        for prev_course, next_course in relations:
            # its 0 indexed now
            in_degrees[next_course - 1] += 1
            self.graph[prev_course - 1].append(next_course - 1)
        return self.recurse((1 << self.n) - 1, tuple(in_degrees))
24000