LeetCode笔记:690. Employee Importance

问题(Easy):

You are given a data structure of employee information, which includes the employee's unique id, his importance value and his 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 his subordinates.

Example 1:
Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.

Note:

  1. One employee has at most one direct leader and may have several subordinates.
  2. 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的下属,但关系不是直接的。

现在给出一个公司的雇员信息,和一个雇员id,你需要返回该雇员及他的下属的总重要值。

例1:
输入:[[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
输出:11
解释:
雇员1有重要值5,他有两个直接下属:雇员2和雇员3。他们都有重要值3,因此雇员1的总重要值是5 + 3 + 3 = 11。

注意:

  1. 一个雇员最多有一个直接领导,但可能有多个下属。
  2. 雇员的最大数量不超过2000。

思路:

乍一看有点麻烦,但其实只是数据结构不再是简单数据类型了,其实还是个递归的解法,先根据目标id找到雇员,记录他的重要值,然后再对其所有下属使用递归计算,这样其下属的下属也会被记录重要值,递归中把所有重要值都加起来就可以了。

代码(C++):

/*
// Employee info
class Employee {
public:
    // It's the unique ID of each node.
    // unique id of this employee
    int id;
    // the importance value of this employee
    int importance;
    // the id of direct subordinates
    vector subordinates;
};
*/
class Solution {
public:
    int getImportance(vector employees, int id) {
        int res = 0;
        for (Employee* employee : employees) {
            if (employee->id == id) {
                res += employee->importance;
                if (employee->subordinates.size() != 0) {
                    for (int subId : employee->subordinates) {
                        res = res + getImportance(employees, subId);
                    }
                }
                break;
            }
        }
        return res;
    }
};

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首页

你可能感兴趣的:(LeetCode笔记:690. Employee Importance)