You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.
Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates.
Example 1:
Note:
One employee has at most one direct leader and may have several subordinates.
The maximum number of employees won't exceed 2000.
员工重要性。
给定一个保存员工信息的数据结构,它包含了员工唯一的id,重要度 和 直系下属的id。 比如,员工1是员工2的领导,员工2是员工3的领导。他们相应的重要度为15, 10, 5。那么员工1的数据结构是[1, 15, [2]],员工2的数据结构是[2, 10, [3]],员工3的数据结构是[3, 5, []]。注意虽然员工3也是员工1的一个下属,但是由于并不是直系下属,因此没有体现在员工1的数据结构中。 现在输入一个公司的所有员工信息,以及单个员工id,返回这个员工和他所有下属的重要度之和。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/employee-importance 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道图论graph的题,不难,搞懂题意就能做的出来。题目给的是所有员工的id,重要度和他们知悉下属的id。既然能拿到当前员工的id,那么拿到当前员工的重要度和他的下属也就不是问题,所以无论是什么做法,我们都需要一个hashmap记住所有员工的重要度和他们各自的下属。至于做法方面,我们可以用BFS或DFS,做法都跟一般的BFS和DFS类型的题非常类似,看了代码应该能懂。
BFS
时间O(V + E)
空间O(V) - number of employees
Java实现
DFS
相关题目
339. Nested List Weight Sum
364. Nested List Weight Sum II
690. Employee Importance
LeetCode 题目总结