There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course ai first if you want to take course bi.
For example, the pair [0, 1] indicates that you have to take course 0 before you can take course 1.
Prerequisites can also be indirect. If course a is a prerequisite of course b, and course b is a prerequisite of course c, then course a is a prerequisite of course c.
You are also given an array queries where queries[j] = [uj, vj]. For the jth query, you should answer whether course uj is a prerequisite of course vj or not.
Return a boolean array answer, where answer[j] is the answer to the jth query.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]]
Output: [false,true]
Explanation: The pair [1, 0] indicates that you have to take course 1 before you can take course 0.
Course 0 is not a prerequisite of course 1, but the opposite is true.
Example 2:
Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]]
Output: [false,false]
Explanation: There are no prerequisites, and each course is independent.
Example 3:
Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]]
Output: [true,true]
Constraints:
- 2 <= numCourses <= 100
- 0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
- prerequisites[i].length == 2
- 0 <= ai, bi <= n - 1
- ai != bi
- All the pairs [ai, bi] are unique.
- The prerequisites graph has no cycles.
- 1 <= queries.length <= 104
- 0 <= ui, vi <= n - 1
- ui != vi
开始想用 union-find 的方式来做, 后来发现对于这种注重中间节点的问题,用 union-find 会比较麻烦。然后就改用 dp。整体思路很简单, 就是找到所有 course 的依赖。
use std::collections::{HashMap, HashSet};
impl Solution {
fn find(prerequisites: &Vec<Vec<i32>>, course: i32, cache: &mut HashMap<i32, HashSet<i32>>) -> HashSet<i32> {
if let Some(c) = cache.get(&course) {
return c.clone();
}
let mut ans = HashSet::new();
for &p in &prerequisites[course as usize] {
ans.insert(p);
let next = Solution::find(prerequisites, p, cache);
ans.extend(&next)
}
cache.insert(course, ans.clone());
ans
}
pub fn check_if_prerequisite(num_courses: i32, prerequisites: Vec<Vec<i32>>, queries: Vec<Vec<i32>>) -> Vec<bool> {
let mut pres: Vec<Vec<i32>> = vec![Vec::new(); num_courses as usize];
for p in prerequisites {
pres[p[1] as usize].push(p[0]);
}
let mut cache = HashMap::new();
let ps: Vec<HashSet<i32>> = (0..num_courses).into_iter().map(|c| Solution::find(&pres, c, &mut cache)).collect();
queries.into_iter().map(|q| ps[q[1] as usize].contains(&q[0])).collect()
}
}

本文通过举例说明如何解决LeetCode中关于课程先修关系的查询问题。当面临依赖关系且不能使用union-find时,采用动态规划(DP)方法找到所有课程的依赖,从而回答查询。
1587

被折叠的 条评论
为什么被折叠?



