[leetcode] Course Schedule II

来源:互联网 发布:mq2烟雾传感器数据手册 编辑:程序博客网 时间:2024/05/16 16:11

From : https://leetcode.com/problems/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].



class Solution { public:     vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {         vector<int> ans;         vector<set<int>> posts(numCourses, set<int>());         vector<int> preNums(numCourses, 0);         for(auto &ab : prerequisites) posts[ab.second].insert(ab.first);         for(int i=posts.size()-1; i>=0; i--) {             for(auto &nd : posts[i]) {                 preNums[nd]++;             }         }         int num = numCourses;         queue<int> q;         for(int i=0; i<num; i++) {             if(preNums[i] == 0) q.push(i);         }        while(!q.empty()) {             int k = q.front();             q.pop();ans.push_back(k);            for(auto &a : posts[k]) {                 if(--preNums[a] == 0) {                     q.push(a);                }             }             num--;         }         if(num > 0) ans.clear();         return ans;     } };


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 考三要练车教练不给练怎么办 科目二指纹打卡指纹不清楚怎么办 教练凶你的时候怎么办 人行聘用制3年后怎么办 道路运输从业资格证过期了怎么办 码头如果要危险运输证怎么办? 7座车怎么办载客营运证 商调函到了原单位不配合怎么办 公司车辆超证了怎么办? 准迁证过期了5年怎么办 天津中派木业不发工资怎么办 在香港餐厅嫌冷怎么办 出国读研报到证怎么办 高中后出国留学档案怎么办 爱迪花园拆了怎么办 燕郊房子卖了户口怎么办 强制险单子丢了怎么办 车辆保险贴丢了怎么办 车险原单子丢了怎么办 车险保单丢了该怎么办? 审车保险单丢了怎么办 湖州公积金贷款买房具体信用怎么办 驾驶本扣分满了怎么办 摩托车被扣12分怎么办 驾照被扣12分怎么办 骑摩托被扣12分怎么办 摩托车没有驾照违章被扣分怎么办 高考登录密码丢了怎么办 高中档案遗失里面体检表怎么办 驾校不给补科一成绩单怎么办 外地驾照转广州体检表怎么办 驾照体检表签名签错怎么办 改完名字后护照怎么办 办健康证没有身份证怎么办 身份证掉了怎么办健康证 华师附小不搬了怎么办 健康证快到期了怎么办 老公想去日本打工怎么办 学生没有资产证明怎么办日本签证 在读证明学校不按模版怎么办 办日本签证没有户口本怎么办