[LeetCode 207] Course Schedule

Leetcode 207. Course Schedule(Python实现) 思路:将边集合构成一个有向图,判断有向图中是否存在环,如果存在环,则一定不能完成该课程;如果不存在环,还需判断,能否遍历到每个结点,如果能遍历到,那么课程能全部完成,则不然。这里判断有向图中是否存在环,用拓扑排序来实现。 class Solution: def canFinish(self, numCourses: int, prerequisites: List[List[int]]... 阅读详情

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, is it possible for you to finish all courses?

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 it is possible.

2, [[1,0],[0,1]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

topological sort, in a directed graph, every time found node without pre-node, then remove all its edges. until iterate all nodes or found cycle.


public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<HashSet> preCourse = new ArrayList<HashSet>();
        for(int i=0;i<numCourses;i++){
            preCourse.add(new HashSet<Integer>());
        }
        for(int i=0;i<prerequisites.length;i++){
            preCourse.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }
        int[] prenums = new int[numCourses];
        for(int i=0;i<numCourses;i++){
            Set set = preCourse.get(i);
            Iterator<Integer> iterator = set.iterator();
            while(iterator.hasNext()){
                prenums[iterator.next()]++;
            }
        }
        for(int i=0;i<numCourses;i++){
            int j=0;
            for(;j<numCourses;j++){
                if(prenums[j]==0) break;
            }
            if(j == numCourses) return false;
            prenums[j] = -1;
            Set set = preCourse.get(j);
            Iterator<Integer> iterator = set.iterator();
            while(iterator.hasNext()){
                prenums[iterator.next()]--;
            }
        }
        return true;
    }



深入C6678启动流程:从BootRom参数表到多核镜像部署的完整解析 本文深入解析TMS320C6678 DSP的启动流程,从BootRom参数表到多核镜像部署的全过程。详细介绍了七种启动模式的工程选择、多核镜像构建技巧以及二级引导策略,帮助开发者掌握C6678的启动机制与调试方法,提升嵌入式系统开发效率。 阅读详情

相关推荐

Zotero搭配CNKI.js插件:一键批量下载知网文献的完整教程(附常见问题解决)

本文提供Zotero搭配CNKI.js插件实现知网文献批量下载的完整教程。详细介绍了从环境准备、插件安装到实战操作的全流程,并针对常见问题提供解决方案,旨在帮助科研人员高效构建自动化文献管理工作流,显著提升文献收集与整理效率。

e4f5g6h7的博客 1203

leetcode:207. 课程表

leetcode:课程表

OceanStar的博客 1359

大学物理第二章 质点动力学详解

大学物理第二章 质点动力学概念详解

weixin_63026364的博客 1万+

【LeetCode刷题记录】207.课程表

你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1。在选修某些课程之前需要一些先修课程。先修课程按数组 prerequisites 给出,其中 prerequisites[i] = [ai, bi] ,表示如果要学习课程 ai 则 必须 先学习课程 bi。例如,先修课程对 [0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1。请你判断是否可能完成所有课程的学习?如果可以,返回 true;否则,返回 false。

C_greenbird的博客 1251

高速设计注意事项总结——MDI篇

在以太网高速通信系统中,MDI(Medium Dependent Interface,介质相关接口)是连接物理层芯片(PHY)与传输介质(如网线)的关键接口,其设计直接影响信号完整性、传输速率和抗干扰能力。本文围绕 MDI 及 RJ45 接口电路、关键参数、设计与布线要点展开,为高速以太网设计提供参考。本文包含MDI 及 RJ45 接口电路组成、电路设计注意事项、布局布线要求等内容

qq_16237389的博客 1446

新硬盘到手,在统信UOS或麒麟系统上怎么认?保姆级教程从识别到挂载一步到位

本文提供新硬盘在统信UOS或麒麟KYLINOS系统上的完整配置指南,从识别物理硬盘到挂载全流程详解。通过终端命令如df和lsblk,帮助用户完成硬盘识别、分区、文件系统创建及挂载配置,确保新硬盘顺利投入使用。

weixin_30698297的博客 443

leetcode(力扣) 207. 课程表1+2(图的构造与遍历,清晰思路,完整模拟)

chudu = [[1, 2], [3], [3], []] 即 i号课的出度指向 chudu[i]假设有:[[3, 0], [3, 1], [4, 1], [4, 2], [5, 3], [5, 4]]输入:numCourses = 2, prerequisites = [[1,0],[0,1]]例如,先修课程对 [0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1。比如对于:[[1,0],[2,0],[3,1],[3,2]]后面就简单了,比如有[1,2] ,图表示就是2->1。

深度不学习!!的博客 568

33、AI赋能5G/6G通信:LDPC码解码与强化学习技术解析

本文探讨了基于AI和强化学习的LDPC码技术在5G/6G通信中的应用。包括LAMS解码器、神经MS解码器、盲识别方法、统一极性-LDPC解码器、NNMS和SNNMS解码器、N-2D-NMS解码器、神经分层MS解码器、MAB-NS方案以及强化学习与MCTS结合的技术。这些技术在提升解码性能、降低计算复杂度和增强系统适应性方面表现出色,为未来通信系统的发展提供了强有力的支持。

lambda的博客 243

leetcode 207. 课程表题解

leetcode 207 课程安排

xuan971130的博客 1532

【大数据Java基础-Java基础01】环境搭建(一)Sublime Text3搭建Java编译环境(Windows系统)

1. 首先配置好Java环境变量 我的jdk版本是1.8.0_191,存放目录是C:\Program Files\Java,因此添加以下环境变量 (1)系统变量→新建 JAVA_HOME 变量,变量值为: C:\Program Files\Java\jdk1.8.0_191 (2)系统变量→找到 Path 变量→编辑,末尾加入: ;%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin 如果Path变量末尾本身有“;”,则上述路径前面则不需要加“;” (3)系统变量→新建 CL

微信搜:import_bigdata,大数据领域硬核原创作者 556

遗传算法(GA)全面解析:从生物基础到工程实践

本文全面解析了遗传算法(GA),从其生物基础到工程实践应用。遗传算法模拟自然进化过程,通过选择、交叉和变异等操作在解空间中高效搜索最优解。文章详细介绍了算法的生物学基础(达尔文进化论、孟德尔遗传定律)、基本概念(种群、个体、基因等)和核心思想。重点阐述了遗传算法的数学模型,包括编码机制、适应度函数设计、遗传算子(选择、交叉、变异)以及关键控制参数。最后提供了一个完整的Python实现示例,展示了遗传算法求解函数最大值问题的具体应用。该算法具有群体搜索、概率导向、无需梯度等特点,适用于各类复杂优化问题。

qq_42212808的博客 1177

【刷题1】LeetCode 207. 课程表 java题解

数据结构学的烂 这都是数据结构留下的坑 至今还未重新学习数据结构 看到一题算一题 题目 https://leetcode-cn.com/problems/course-schedule/ 相关概念 入度:它通常指有向图中某点作为图中边的终点的次数之和。 ** 边缘列表**: 邻接表:储存跟一个顶点相连的顶点 分析 课程安排图是否是 有向无环图(DAG)。 即课程间规定了前置条件,但不能构成任何环路,否则课程前置条件将不成立。 思路是通过 拓扑排序 判断此课程安排图是否是 有向无环图(DAG) 。 .

乾坤未定,你我皆是黑马 762

StarRocks 面试题及参考答案详解(万字详解)

Broker Load的过程通常涉及到数据的解析、转换和加载,它支持多种数据格式,并且可以处理复杂的数据导入任务。一方面,压缩可以减少磁盘I/O操作,因为压缩后的数据占用的空间更小,需要读取的数据块数量也就更少。在StarRocks中,表数据可以被划分成多个分区,每个分区包含表的一部分数据。在传统的行存储模型中,数据是按行组织的,这意味着在执行分析查询时,系统需要读取并处理整行数据,即使很多时候只需要查询其中的少数几列。物化视图的更新可以是完全重算,也可以是增量更新,取决于物化视图的定义和数据变更的模式。

大模型大数据攻城狮的专栏 2083

[leetcode] 207. Course Schedule 解题报告

题目链接:https://leetcode.com/problems/course-schedule/ 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

小榕流光的专栏 1941

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

LeetCode 207. Course Schedule

图和dfs

Llunnn的博客 339

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

LeetCode 207. Course Schedule 题解

本题是拓扑排序的经典问题,主要考察对拓扑排序算法的理解和应用。通过构建邻接表和入度数组,然后使用队列进行拓扑排序,我们可以判断是否存在环,从而确定是否可以完成所有课程的学习。拓扑排序的核心思想是:按照依赖关系的顺序,依次处理入度为 0 的节点。如果最终所有节点都被处理,说明不存在环;否则,说明存在环。这种方法不仅适用于课程表问题,还可以应用于许多其他需要处理依赖关系的场景,例如任务调度、编译顺序等。掌握拓扑排序的思想,对于解决这类问题非常重要。

cannonjinx的博客 4265

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

leetcode题集: 207. Course Schedule

上次写了关于拓扑排序的写法,今天这个题就是关于拓扑排序的应用与改进。 第12题:207.Course Schedule 文章大意:课程安排,课程之间有依赖性。给定课程数,和课程之间的依赖,判断课程能否顺利完成。 题目分析:这不就是之前写的拓扑排序能干嘛吗?所以这是一个拓扑排序的问题,所以啊直接开始干。要注意的是,后面给数组中,后面一个表示前驱节点。即[1,0]表示的是0->1. ...

wx_14678的博客 299

[leetcode] 207. Course Schedule

Description 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 expresse...

Learning from the mistakes 240

Leetcode 207 Course Schedule

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

无名山丘,崛起成峰 1059

Leetcode 207 Course Schedule 课程表

你需要上n个课程,标记为0~n-1。有些课程有前导课,比如你要上课程0必须先上课程1,我们用一个整数对[0,1]来表示。给出课程的总数和一系列的课程先导关系对,判断是否可能上完所有的课程。

(ง •̀_•́)ง 6515

leetcode 207: Course Schedule

leetcode 207 : Course Schedule

西施豆腐渣 5423

LeetCode 207 Course Schedule

LeetCode 207 Course Schedule 题意 有0~n-1共n门课你需要进修,其中一些课程需要在修完其他课程后才能进修,例如(0,1)表示要进修课程0你必须先修完课程1。给出课程的总数以及一个列表表示所有的先决条件,问是否可能修完所有课程。 注: 课程先决条件可以看作是由一个图的边(edge)组成 不会出现重复的边 思路 假如将每个先决条件(a,b)看作是b到a的有向边,整个...

EricJeffrey的博客 164

LeetCode207 Course Schedule

LeetCode207 Course Schedule问题描述 here 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 co

yanqinghe123的专栏 374

【LEETCODE】207-Course Schedule

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 p

aliceyangxi1987的博客 746

LeetCode 207. Course Schedule && LeetCode 210. Course Schedule II

LeetCode 207. Course Schedule && LeetCode 210. Course Schedule II (Medium) 主要知识点:拓扑排序、BFS、DFS;优先级:5

温迪今天刷题了吗 981
上一篇: [LeetCode179] Largest Number
下一篇: [LeetCode206] Course Schedule II
Mavs
博客等级 码龄17年 166粉丝 296原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值