以前从来没有写过解题报告,只是看到大肥羊河delta写过不少。最近想把写博客的节奏给带起来,所以就挑一个比较容易的题目练练手。

原题链接

https://leetcode.com/problems/course-schedule/

题目大意

有n个课程,编号分别是0到n-1。我们的目标是修完所有课程。然而有些课程有前置课程的,我们必须修完前置课程才能修该门课程。题目给了我们课程之间的前置关系,让我们判断是否能修完所有课程。

题目原型

这个题目的描述简单粗暴,我们不难发现,其实是给了我们一个有向图,然后问我们这个图里面是否存在环。

解题思路

我们的目的也非常直观,就是判断一个有向图是否存在环。

我想到的是用dfs。首先构造出一棵树(当然不一定是真正的树,因为有可能存在环;也有可能是多棵树)。然后对每棵树进行深搜,一旦发现某个节点和它的祖先节点相同,就存在环。这里给出一份伪代码。其中processed状态并不是必须的,只是为了避免一些不必要的重复搜索。

// 伪代码
foreach node
{
if (node is not processed)
dfs(node);
} dfs(node)
{
mark node as processed
mark node as visiting
foreach childNode
{
if (node is visiting)
{
find circle and stop;
}
if (childNode is not processed)
{
dfs(childNode)
}
}
mark node as not visiting
}

不过我最后并没有用这种方法,而是用了一个叫做Kahn的拓扑排序典型算法。让我来介绍一下这个算法的流程(其实很简单,一看包会)。

// L 储存最终有序结果的List
// S 储存所有不存在入边的节点,即入度为0的点的集合
while S is not empty
get a node x from S
append x to list L
foreach node that has an edge from x(e.g. x -> y)
remove that edge
if y doesn't contain any income edges
add y to set S if L contains all the nodes
succeed
else
fail

这个算法的精髓在于维护了一个入度为0的点的集合(这个集合可以是set,array,list等,非常自由),每次处理掉一个0入度的点,然后把新产生的0入度的点添加到该集合。

结合我们的题目,可以发现这个算法可以直接应用到我们这个题上来,而不需要任何的额外改变。所以我就直接贴代码了。

public boolean canFinish(int numCourses, int[][] prerequisites) {
// 个人习惯,判断一下特殊情况
if (numCourses <= 1 || prerequisites == null)
{
return true;
}
Stack<Integer> out[] = new Stack[numCourses]; // 所有的边
for (int i = 0; i < numCourses; i++)
{
out[i] = new Stack<Integer>();
} int[] in = new int[numCourses]; // 统计入度的数组
for (int i = 0; i < prerequisites.length; i++)
{
out[prerequisites[i][0]].push(prerequisites[i][1]);
in[prerequisites[i][1]]++;
} Stack<Integer> noneIn = new Stack<Integer>(); // 集合S
int res = 0; // 由于并不需要最终的排序结果,所以只记录了L中的个数 for (int i = 0; i < numCourses; i++)
{
if (in[i] == 0)
{
noneIn.push(i);
}
} while (!noneIn.isEmpty())
{
int x = noneIn.pop();
res++;
while (!out[x].isEmpty())
{
int y = out[x].pop();
if (--in[y] == 0)
{
noneIn.push(y);
}
}
} return res == numCourses;
}

LeetCode - Course Schedule 解题报告的更多相关文章

  1. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  2. 【LeetCode】Permutations 解题报告

    全排列问题.经常使用的排列生成算法有序数法.字典序法.换位法(Johnson(Johnson-Trotter).轮转法以及Shift cursor cursor* (Gao & Wang)法. ...

  3. LeetCode: Sort Colors 解题报告

    Sort ColorsGiven an array with n objects colored red, white or blue, sort them so that objects of th ...

  4. 【LeetCode】207. Course Schedule 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/course-s ...

  5. LeetCode: Permutation Sequence 解题报告

    Permutation Sequence https://oj.leetcode.com/problems/permutation-sequence/ The set [1,2,3,…,n] cont ...

  6. Leetcode:Interleaving String 解题报告

    Interleaving StringGiven s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For ...

  7. Leetcode:Scramble String 解题报告

    Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two no ...

  8. LeetCode: Gas Station 解题报告

    Gas Station There are N gas stations along a circular route, where the amount of gas at station i is ...

  9. LeetCode: Palindrome Partitioning 解题报告

    Given a string s, partition s such that every substring of the partition is a palindrome. Return all ...

随机推荐

  1. Windows下实现mysql定时备份

    1.写MySQL备份bat处理 @echo off set "yMd=%date:~,4%%date:~5,2%%date:~8,2%" set "hms=%time:~ ...

  2. C++输入/输出流

    2017-08-17 09:03:28 writer:pprp 基本的输入/输出流 默认情况下,输入操作会丢弃前导空白,读取数据,遇到空白的时候停止读入: 如果希望的如包括空白在内的任意字符,可以使用 ...

  3. [小问题笔记(六)] 解决JS已执行,输出内容乱码问题. 顺带总结编码相关知识

    问题: JS输出的内容出现了乱码.如图: 分析:既然年和月的数字可以正常显示,证明js加载和执行都没有问题 解决:把js引用处的编码方式改成当前页面编码一致.charset="gb2312& ...

  4. poj 2255 Tree Recovery 分治

    Tree Recovery Description Little Valentine liked playing with binary trees very much. Her favorite g ...

  5. LeetCode第[84]题(Java):Largest Rectangle in Histogram(最大的矩形柱状图)

    题目:最大的矩形柱状图 难度:hard 题目内容: Given n non-negative integers representing the histogram's bar height wher ...

  6. iOS开发调试技巧总结(持续更新中)

    作者:乞力马扎罗的雪  原文 对于软件开发而言,调试是必须学会的技能,重要性不言而喻.对于调试的技能,基本上是可以迁移的,也就是说你以前在其他平台上掌握的很多调试技巧,很多也是可以用在iOS开发中.不 ...

  7. IOS-每个程序员的编程之路上都应该看这11本书

    国外知名网站stackoverflow上有一个问题调查: 哪本书是对程序员最有影响.每个程序员都该阅读的书?,这个调查已历时两年,目前为止吸引了153,432人访问,读者共推荐出了478本书(还在增加 ...

  8. Ansible 小手册系列 十二(Facts)

    Facts 是用来采集目标系统信息的,具体是用setup模块来采集得. 使用setup模块来获取目标系统信息 ansible hostname -m setup 仅显示与ansible相关的内存信息 ...

  9. Netty实例几则

    Netty是基于JDK NIO的网络框架 简化了NIO编程, 不用程序自己维护selector, 将网络通信和数据处理的部分做了分离 多用于做底层的数据通信, 心跳检测(keepalived) 1. ...

  10. h5和app原生联调触发方法

    //路径跳转 urlHref(item) {//人物.访谈.动态是一个页面 var para = {}; para.title = "动态详情"; para.type = &quo ...