超出时间限制的解法
- 构建prerequisites维零矩阵Q,若[i,j]在prerequisites中,则第j行i列为1
- 遍历每一列,若k列全为0,则门课程没有先修课程,将k加入result,之后不再遍历k列,并将Q中k行元素设为0
- 重复步骤二prerequisites次
import numpy as np
def findOrder(numCourses,prerequisites):
if prerequisites == []:
return list(range(0, numCourses))
result = []
Q = [[0] * numCourses] * numCourses
Q = np.array(Q)
for item in prerequisites:
Q[item[1]][item[0]] = 1
b = list(range(0, numCourses))
for k in range(numCourses):
count = 0
flag = len(b)
for j in b:
if np.max(Q[:, j]) == 1:
count += 1
else:
result.append(j)
b.remove(j)
Q[j, :] *= 0
break
if (count == flag):
return []
if (len(result) != numCourses):
return []
return result
高效正解:
https://leetcode-cn.com/problems/course-schedule-ii/solution/ke-cheng-biao-ii-by-leetcode-solution/