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.
  • You may assume that there are no duplicate edges in the input prerequisites.

和之前做过的Course Schedule类似,其实就是拓扑排序。代码如下:

class Solution {
public:
    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int>> map(numCourses);
        vector<int> in(numCourses, 0);
        auto n = prerequisites.size();
        for (auto i=0; i<n; i++) {
            map[prerequisites[i].second].push_back(prerequisites[i].first);
            in[prerequisites[i].first]++;
        }
        vector<int> res;
        while (res.size() < numCourses) {
            auto i = 0;
            for (i=0; i<numCourses; i++)
                if (in[i] == 0)
                    break;
            if (i == numCourses)
                return vector<int>();
            res.push_back(i);
            in[i] = -1;
            for (auto j=0; j<map[i].size(); j++)
                in[map[i][j]]--;
        }
        return res;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,436评论 0 23
  • 和大家一样,准备來意大利的我也是又兴奋叉不知所措的,临行前的准备肯定已经开始很久了,以我个人的经验來说,我当時特别...
    SilviaBB阅读 1,014评论 0 0
  • 再怎么不舍,日子也一天天过去了。眨眼间,不过几日圆圆就要嫁给徐家。 这几日,柳咏更是忙得上下不接。女儿嫁给徐家本就...
    想要忘记阅读 1,261评论 0 0
  • 读猫叔的文章,读的越多,自己的心态就会变得越来越好,成为一个价值投资者。 在以前都是因为心态不好,...
    无悔岁月阅读 845评论 0 0
  • 笔耕不辍之任何年龄都不晚 做健康直播三个多月了,看到在直播时很多朋友问的问题很有意思。其中有人会问:我五十多了,六...
    理疗瑜伽邵阅读 1,690评论 0 0