赞
踩
你总共需要上 n 门课,课程编号依次为 0 到 n-1 。
有的课会有直接的先修课程,比如如果想上课程 0 ,你必须先上课程 1 ,那么会以 [1,0] 数对的形式给出先修课程数对。
给你课程总数 n 和一个直接先修课程数对列表 prerequisite 和一个查询对列表 queries 。
对于每个查询对 queries[i] ,请判断 queries[i][0] 是否是 queries[i][1] 的先修课程。
请返回一个布尔值列表,列表中每个元素依次分别对应 queries 每个查询对的判断结果。
记忆深度搜索
class Solution { List<List<Integer>> adjoin = new ArrayList<>(); int[][] memory; List<Boolean> res = new ArrayList<>(); public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { int n = numCourses; memory = new int[n][n]; for(int i = 0; i < n; i++){ adjoin.add(new ArrayList<>()); } for(int i = 0; i < prerequisites.length; i++){ adjoin.get(prerequisites[i][0]).add(prerequisites[i][1]); } for(int i = 0; i < queries.length; i++){ res.add(dfs(queries[i][0],queries[i][1])); } return res; } public boolean dfs(int a, int b){ if(memory[a][b] == 1 || a == b){ return true; } if(memory[a][b] == -1){ return false; } List<Integer> li = adjoin.get(a); for(int i : li){ if(dfs(i,b)){ memory[i][b] = 1; return true; } } memory[a][b] = -1; return false; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。