LeetCode 210 Course Schedule II

来源:互联网 发布:excel的数据统计分析 编辑:程序博客网 时间:2024/05/17 00:12

LeetCode 210 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].

问题分析

这道题是LeetCode207 Course Schedule的变形问题,之前的题目是判断课程设置是否合适。这里不光要判断课程是否合适,还需要返回一种合理的上课方案。其实改变起来也挺简单的,就是完成一次迭代,看看是否将所有的课程都纳入,如果没有纳入,说明在本次迭代中出现了环,就是上一道题中的[0,1][1,0]这种情况。

这次的思路就是从后往前遍历,首先将那么些不是别的课程的依赖的课加入Quene,然后开始对Quene首的元素进行判断,这里需要注意,因为有些课可能是多个课的前提。比如[1,0],[2,0],[3,0]其中0是1,2,3的前提,所以说,在一门课的后续课程没有遍历完之前,不能将该课程放入Quene。不然最后会导致一些课的安排在前提课程的前面。

代码如下

Java

public int[] findOrder(int numCourses, int[][] prerequisites) {           //初始化节点数组    List<Integer>[] nodes = new ArrayList[numCourses];    //    int[] isReq = new int[numCourses];    for (int i = 0; i < numCourses; i++) {        nodes[i]=new ArrayList<>();    }    //初始化节点之间的关系    //isReq代表是否是别的节点的前提    for (int[] prerequisite : prerequisites            ) {        nodes[prerequisite[0]].add(prerequisite[1]);        isReq[prerequisite[1]]++;    }    Queue<Integer> queue = new ArrayDeque<>();    for (int i = 0; i <numCourses ; i++) {        if(isReq[i]==0) queue.add(i);    }    int [] res = new int[numCourses];    int count = numCourses-1;    while (!queue.isEmpty()){        int temp = queue.remove();        res[count--]=temp;        for (Integer child:nodes[temp]){            isReq[child]--;            if(isReq[child]==0) queue.add(child);        }    }    if(count!=-1) return new int[0];    return res;}

LeetCode学习笔记持续更新
GitHub地址 https://github.com/yanqinghe/leetcode
CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678

原创粉丝点击