<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>

from itertools import combinations
from typing import List
from functools import lru_cache

class Solution:
    def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:

        # Set up prerequisite counts and dependent course lists
        dependent_courses = {i: [] for i in range(1, n + 1)}
        how_many_preq = [0 for _ in range(n + 1)]  # 1-based index

        for preq, course in relations:
            dependent_courses[preq].append(course)
            how_many_preq[course] += 1

        courses_left = (1 << n) - 1  # All n bits set to 1

        @lru_cache(None)
        def rec(how_many_preq_tuple, courses_left):
            how_many_preq = list(how_many_preq_tuple)
            
            # Base case: no courses left
            if courses_left == 0:
                return 0
            
            possible_takes = []
            
            # Find all possible courses to take (those with no prerequisites)
            for course_ID in range(1, n + 1):
                if courses_left & (1 << (course_ID - 1)) and how_many_preq[course_ID] == 0:
                    possible_takes.append(course_ID)

            # If fewer possible courses than k, only take those
            min_courses = min(k, len(possible_takes))
            result = float('inf')
            
            # Try all combinations of up to k possible courses
            for k_possibilities in combinations(possible_takes, min_courses):
                how_many_preq_copy = how_many_preq[:]
                courses_left_copy = courses_left
                
                for course_ID in k_possibilities:
                    courses_left_copy ^= (1 << (course_ID - 1))  # Mark course as taken
                    for dep_course in dependent_courses[course_ID]:
                        how_many_preq_copy[dep_course] -= 1  # Reduce prerequisites for dependent courses
                
                # Recursively calculate semesters for the next state
                result = min(result, 1 + rec(tuple(how_many_preq_copy), courses_left_copy))
            
            return result

        return rec(tuple(how_many_preq), courses_left)
23700