Link : https://leetcode.com/problems/employee-importance/
Problem :
You have a data structure of employee information, which includes the employee’s unique id, their importance value, and their direct subordinates’ id.
You are given an array of employees employees
where:
employees[i].id
is the ID of theith
employee.employees[i].importance
is the importance value of theith
employee.employees[i].subordinates
is a list of the IDs of the subordinates of theith
employee.
Given an integer id
that represents the ID of an employee, return the total importance value of this employee and all their subordinates.
給一個id(整數),加總所有importance value。
Thoughts :
1. 先把整個employees的 list拆開成 importance跟subordinates。
2. 分別存入不同的dictionary。
3. 用遞迴來找,先記錄 id 的 importance 為 res,如果這個 employee 有subordinates 就把它加上 res,直到結束。
Solution :
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""class Solution:
def getImportance(self, employees: List['Employee'], id: int) -> int:
dic = {}
sub = {}
for employee in employees:
dic[employee.id] = employee.importance
sub[employee.id] = employee.subordinates
def help(id):
res = dic[id]
for sub_id in sub[id]:
res += help(sub_id)
return res
return help(id)
time complexity = O(n), space complexity = O(n)
Note : n is number of employees