Solution: python3


  • 0
    P

    """

    Employee info

    class Employee:
    def init(self, id, importance, subordinates):
    # It's the unique id of each node.
    # unique id of this employee
    self.id = id
    # the importance value of this employee
    self.importance = importance
    # the id of direct subordinates
    self.subordinates = subordinates
    """

    class Solution:

    def getImportance(self, employees, id):
        i = -1
        present = -1
    
        #looping through the list of employees to check if id exists
        for employee in employees:
            if id == employee.id :
                present = 1
                #capture the index of current employee in the list
                i = employees.index(employee)
                break
    
        #base case for recursion
        if present == -1:
            #print("id not found!")
            return 0
    
        #importance value for current employee
        imp = employees[i].importance
    
        #using recursive algorithm to find subordinate's importance
        for sub in employees[i].subordinates:
            #keep adding importance values of subordinates
            imp += self.getImportance(employees, sub)
        
        #print("total imp: ",imp)
        return imp

  • 0
    Y

    ···

    /*
    // 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) {
    
        int sum = 0;
        for(Employee e:employees){
            if(e.id == id){
                sum += e.importance;
                List<Integer> sub = e.subordinates;
                if(sub.size()!=0){//不为空
                    for(Employee em:employees){
                        if(belong(sub,em.id)){
                           sum += getImportance(employees,em.id);
                        }                        
                    }
                     return sum;
                }
                else{
                    return e.importance;
                }                
            }
        }
        return sum;
    }
    public boolean belong(List<Integer> sub, int id){
        for(Integer s:sub){
            if(s==id)
                return true;
        }
        return false;
    }
    

    }
    ···


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.