leetcode 690. 員工的重要性
阿新 • • 發佈:2018-11-07
給定一個儲存員工資訊的資料結構,它包含了員工唯一的id,重要度 和 直系下屬的id。
比如,員工1是員工2的領導,員工2是員工3的領導。他們相應的重要度為15, 10, 5。那麼員工1的資料結構是[1, 15, [2]],員工2的資料結構是[2, 10, [3]],員工3的資料結構是[3, 5, []]。注意雖然員工3也是員工1的一個下屬,但是由於並不是直系下屬,因此沒有體現在員工1的資料結構中。
現在輸入一個公司的所有員工資訊,以及單個員工id,返回這個員工和他所有下屬的重要度之和。
示例 1:
輸入: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1 輸出:11 解釋: 員工1自身的重要度是5,他有兩個直系下屬2和3,而且2和3的重要度均為3。因此員工1的總重要度是 5 + 3 + 3 = 11。
注意:
- 一個員工最多有一個直系領導,但是可以有多個直系下屬
- 員工數量不超過2000。
解法:
一看題目就是經典的dfs。
程式碼1:
""" # Employee info class Employee(object): 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(object): def getImportance(self, employees, id): """ :type employees: Employee :type id: int :rtype: int """ sum=0 for employee in employees: if id==employee.id: sum+=employee.importance for subordinate in employee.subordinates: sum+=self.getImportance(employees,subordinate) return sum
程式碼2:
""" # Employee info class Employee(object): 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(object): def getImportance(self, employees, id): """ :type employees: Employee :type id: int :rtype: int """ def dfs(root,_dict): if not root: return 0 return root.importance+sum([dfs(_dict[sub],_dict) for sub in root.subordinates]) _dict={e.id:e for e in employees} return dfs(_dict[id],_dict)