# 690. 员工的重要性

输入：[[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1



• 一个员工最多有一个 直系 领导，但是可以有多个 直系 下属
• 员工数量不超过 2000 。

"""
# 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:
res=0
for e in employees:
if e.id==id:
res+=e.importance
subordinate=e.subordinates
break
for e in employees:
if e.id in subordinate:
res+=e.importance
if e.subordinates:
for i in e.subordinates:
res+=self.getImportance(employees,i)
return res

"""
# 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:
for e in employees:
if e.id==id:
if not e.subordinates:
return e.importance
for i in e.subordinates:
e.importance+=self.getImportance(employees,i)
return e.importance
return 0

dict+递归

"""
# 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:
dict={}
for e in employees:
dict[e.id]=e
def helper(dict,id):
e=dict[id]
for i in e.subordinates:
e.importance+=helper(dict,i)
return e.importance
return helper(dict,id)

stack or queue

"""
# 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:
dict={}
for e in employees:
dict[e.id]=e
q=[dict[id]]
res=0
while q:
e=q.pop(0)
res+=e.importance
for i in e.subordinates:
q.append(dict[i])
return res

posted @ 2021-05-01 12:24  XXXSANS  阅读(158)  评论(0编辑  收藏  举报