zoukankan      html  css  js  c++  java
  • Leetcode** 210. Course Schedule II

    Description: There are a total of n courses you have to take labelled from 0 to n - 1.

    Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai.

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

    If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.

    Link: 210. Course Schedule II

    Examples:

    Example 1:
    Input: numCourses = 2, prerequisites = [[1,0]]
    Output: [0,1]
    Explanation: 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]. Example 2: Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] Output: [0,2,1,3] Explanation: 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]. Example 3: Input: numCourses = 1, prerequisites = [] Output: [0]

    思路: 这道题是207的升级版,需要在可以成功安排所有课程的情况下,返回任意一种安排方式。因为不是返回所有可能的结果,就变得简单很多。只需要在207的基础上,添加一条路径。

    class Solution(object):
        def findOrder(self, numCourses, prerequisites):
            """
            :type numCourses: int
            :type prerequisites: List[List[int]]
            :rtype: List[int]
            """
            self.pre = collections.defaultdict(list)
            for p in prerequisites:
                self.pre[p[0]].append(p[1])
            self.visited = [0]*numCourses
            self.path = []
            for i in range(numCourses):
                if not self.dfs(i):
                    return []
            return self.path
        
        def dfs(self, i):
            if self.visited[i] == 1: return True
            if self.visited[i] == 2: return False
            self.visited[i] = 2
            for b in self.pre[i]:
                if not self.dfs(b): return False
            self.visited[i] = 1
            self.path.append(i)
            return True

    日期: 2021-04-20  时光不辜负

  • 相关阅读:
    2019-07-15_nginx 启动报错 “/var/run/nginx/nginx.pid" failed” 解决方法
    2019-07-12 linux下关闭、开启防火墙
    2019-07-12nginx的安装,启动,关闭
    2019-07-11 nginx 下网页显示乱码
    2019-07-05 submit左对齐快捷键
    2019-07-02 windows下用cmd命令netstat查看系统端口使用情况
    设计一个精致按钮
    JS 实现省市三级联动
    使用style 对象实现图片的覆盖(overlay)
    display 显示或隐藏元素
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14680683.html
Copyright © 2011-2022 走看看