(LC)690. The importance of employees

690. The importance of employees

Given a data structure that saves employee information, it contains the employee's unique id, importance, and the id of the immediate subordinates.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. Their corresponding importance is 15, 10, 5. Then the data structure of employee 1 is [1, 15, [2]], the data structure of employee 2 is [2, 10, [3]], and the data structure of employee 3 is [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, because it is not a direct subordinate, it is not reflected in the data structure of employee 1.

Now enter all employee information of a company and a single employee id to return the sum of the importance of this employee and all his subordinates.

Example 1:

Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1’s own importance is 5, he There are two direct subordinates 2 and 3, and the importance of 2 and 3 is 3. Therefore, the total importance of employee 1 is 5 + 3 + 3 = 11.
note:

An employee can have at most one direct leader, but there can be multiple direct subordinates. The
number of employees does not exceed 2000

/*
// Definition for Employee.
class Employee {
    public int id;
    public int importance;
    public List<Integer> subordinates;
};
*/
 public int getImportance(List<Employee> employees, int id) {
    
    
        int sum=0;
        for(Employee e:employees) {
    
    
            if (e.id == id) {
    
    
                if(e.subordinates.size() == 0) {
    
    
                    return e.importance;
                }
                for (int subId:e.subordinates) {
    
    
                    e.importance+=getImportance(employees,subId);
                }
                return e.importance;
            }
        }
        return 0;
    }

Guess you like

Origin blog.csdn.net/weixin_45567738/article/details/114708079