Leetcode of depth-first search (DFS) -690 topic. The importance of employees (Employee Importance)

Leetcode of depth-first search (DFS) -690 topic. The importance of employees (Employee Importance)

Problem-solving depth-first search details, click


 

Given a data structure stored employee information, it contains a unique id employees, and the importance of immediate subordinates id.

For example, the staff is 1 staff leadership 2, 2 employees employee leadership 3. The importance of their respective 15, 10, 5. Then the structure of employee data is [1, 15, [2]], employee data structure 2 is [2, 10, [3]] data structure, the staff is 3 [3, 5, []]. Note that though a subordinate employee staff is 3 1, but since not immediate subordinates, and therefore not reflected in the data structure of employees 1.

Now enter a company all the employee information, and a single employee id, and returns the employees of the importance of his subordinates and all.

Example 1:

Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 
Output: 11 
Explanation: 
employee 1 importance degree itself is 5, he there are two immediate subordinates 2 and 3, and the importance of 2 and 3 are 3. Thus the overall importance of the employee is 5 + 3 1 + 3 = 11.

note:

  1. An employee has at most one direct leadership, but can have more immediate subordinates
  2. The number of employees does not exceed 2,000.

  


 

It has been searching subordinate nodes and superimposed importance value.

/*
// Employee info
class Employee {
    // It's the unique id of each node;
    // unique id of this employee
    public int id;
    // the importance value of this employee
    public int importance;
    // the id of direct subordinates
    public List<Integer> subordinates;
};
*/
class Solution {
    public int getImportance(List<Employee> employees, int id) {
        Employee person = null;
        for(Employee e:employees){
            if(e.id==id){
                person = e;
                break;
            }
        }
        
        List<Integer> sub_list = person.subordinates;
        int sum = 0;
        for(int i=0;i<sub_list.size();i++){
            sum += getImportance(employees,sub_list.get(i));
        }
        return person.importance + sum;
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11361411.html