【LeetCode】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 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.

【解析】

典型的拓扑排序。原理也很简单,在一个有向图中,每次找到一个没有前驱节点的节点(也就是入度为0的节点),然后把它指向其他节点的边都去掉,重复这个过程(BFS),直到所有节点已被找到,或者没有符合条件的节点(如果图中有环存在)。

回顾一下图的三种表示方式:边表示法(即题目中表示方法),邻接表法,邻接矩阵。用邻接表存储图比较方便寻找入度为0的节点。

【Java代码】

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        // init the adjacency list
        List<Set> posts = new ArrayList<Set>();
        for (int i = 0; i < numCourses; i++) {
            posts.add(new HashSet<Integer>());
        }

        // fill the adjacency list
        for (int i = 0; i < prerequisites.length; i++) {
            posts.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }

        // count the pre-courses
        int[] preNums = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            Set set = posts.get(i);
            Iterator<Integer> it = set.iterator();
            while (it.hasNext()) {
            	preNums[it.next()]++;
            }
        }

        // remove a non-pre course each time
        for (int i = 0; i < numCourses; i++) {
            // find a non-pre course
            int j = 0;
            for ( ; j < numCourses; j++) {
                if (preNums[j] == 0) break;
            }

            // if not find a non-pre course
            if (j == numCourses) return false;

            preNums[j] = -1;

            // decrease courses that post the course
            Set set = posts.get(j);
            Iterator<Integer> it = set.iterator();
            while (it.hasNext()) {
            	preNums[it.next()]--;
            }
        }

        return true;
    }
}

注意,输入可能有重复的边,所以邻接表用HashSet存储。

下面一种代码是不用HashSet的,对于重复的边,它在邻接表中村了两份,同时计算入度时也算了两次,所以代码不会有问题。但个人感觉最好用HashSet,这样符合图的定义。

下面的代码还是比较典型的BFS写法,大家可以对比理解下:

public class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<List<Integer>> posts = new ArrayList<List<Integer>>();
        for (int i = 0; i < numCourses; i++) {
            posts.add(new ArrayList<Integer>());
        }

        int[] preNums = new int[numCourses];
        for (int i = 0; i < prerequisites.length; i++) {
            posts.get(prerequisites[i][1]).add(prerequisites[i][0]);
            preNums[prerequisites[i][0]]++;
        }

        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i = 0; i < numCourses; i++) {
            if (preNums[i] == 0){
                queue.offer(i);
            }
        }

        int count = numCourses;
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            for (int i : posts.get(cur)) {
                if (--preNums[i] == 0) {
                    queue.offer(i);
                }
            }
            count--;
        }

        return count == 0;
    }
}
时间: 2024-12-21 14:25:55

【LeetCode】Course Schedule 解题报告的相关文章

LeetCode: Combination Sum 解题报告

Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Question Solution Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The

[LeetCode]LRU Cache, 解题报告

题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

poj 1325 Machine Schedule 解题报告

题目链接:http://poj.org/problem?id=1325 题目意思:有 k 个作业,机器A有 n 个模式:0 ~ n-1,机器B 有 m 个模式:0~ m-1.每一个作业能运行在 A 的 某一个模式(假设为 i (0 <= i <= n-1 ) )或 B 的某一个模式下(j (0 <= j <= m-1)).多个作业可以同时运行在 A 的某一个 模式下,当然 B 也如此.每对A 或 B 转换一次模式,就要重启一次 A 或者 B,你需要选择A 或 B 的一些模式,使得所

【LeetCode】Subsets 解题报告

[题目] Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,

LeetCode ZigZag Conversion 解题报告

对输入字符串,做蛇形变化,然后按行输出. https://oj.leetcode.com/problems/zigzag-conversion/ 例如:The string "PAYPALISHIRING"  的蛇形变化如下: P        A           H        N A   P   L    S     I     I   G Y         I            R 最后要求输出的就是:"PAHNAPLSIIGYIR" Write

LeetCode: Gas Station 解题报告

Gas Station There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journ

Leetcode:Interleaving String 解题报告

Interleaving StringGiven s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = "aabcc",s2 = "dbbca", When s3 = "aadbbcbcac", return true.When s3 = "aadbbbaccc", return false.

Leetcode:Scramble String 解题报告

Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / gr eat / \ / g r e at / a t To scramble the string,

LeetCode: Merge Intervals 解题报告

Merge IntervalsGiven a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,10],[15,18],return [1,6],[8,10],[15,18]. SOLUTION 1: 1. 先使用Comparator 的匿名类对intervels进行排序. 2. 把Intervals遍历一次,依次一个一个merge到第1个interval. 把第1