题目链接:Course Schedule II

There are a total of n courses you have to take, labeled from 0 to n - 1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

For example:

2, [[1,0]] 

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1]

4, [[1,0],[2,0],[3,1],[3,2]] 

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is[0,2,1,3].

Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

Hints:

  1. This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
  2. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
  3. Topological sort could also be done via BFS.

这道题的要求是课程安排:有n门课,编号0~n-1。有一些课程需要有先决条件,例如选修课程0你必须首先选修课程1,表示为[0, 1]。给出课程总数以及课程的先决条件,返回一个可以修完所有课程的序列。

Course Schedule类似的题目,同样可以注意到课程的先决条件之间的关系,构成了有向图。而找到一个可以修完所有课程的序列是找到一个拓扑序列。

记录每个节点的入度,然后找入度为0的节点,直到找完所有节点。如果没有找到入度为0的节点(没有找完所有节点),说明有环,无法构成拓扑序列,直接返回空vector。

同时,在找到入度为0的节点后,记录该节点下标,同时需要删除其节点(可以将该节点入度标志位-1),同时将该节点的后继节点的入度均减1,说明该节点对应的课程已经修完了。

需要注意一个问题,由于存在重复的先决条件,因此在生成有向图和统计入度的时候,需要特殊处理或者分布进行。

时间复杂度:O(n2)

空间复杂度:O(n2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution
{
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites)
    {
        vector<unordered_set<int>> matrix(numCourses); // 邻接表
        
        for(int i = 0; i < prerequisites.size(); ++ i)
            matrix[prerequisites[i].second].insert(prerequisites[i].first);
        
        vector<int> d(numCourses, 0); // 入度
        for(int i = 0; i < numCourses; ++ i)
            for(auto it = matrix[i].begin(); it != matrix[i].end(); ++ it)
                ++ d[*it];
        
        vector<int> res(numCourses);
        for(int j = 0, i; j < numCourses; ++ j)
        {
            for(i = 0; i < numCourses && d[i] != 0; ++ i);
            
            if(i == numCourses)
                return {};
            
            res[j] = i;
            d[i] = -1;
            for(auto it = matrix[i].begin(); it != matrix[i].end(); ++ it)
                -- d[*it];
        }
        
        return res;
    }
};