💬 문제
(leetcode.com/problems/employee-importance/)
You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.
For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.
Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates.
💬 코드
"""
# 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:
graph = {e.id: e for e in employees}
def dfs(i):
employee = graph[i]
return employee.importance + sum(dfs(j) for j in employee.subordinates)
return dfs(id)
Employee는 class고 id, importance, subordinates를 속성으로 가지고 있다. 이를 무시하고 속성을 튜플에 저장해서 dfs를 사용하려 했다가 최대 재귀 횟수 초과라는 뼈아픈 실패를 맛봤다.
'Algorithm > Python' 카테고리의 다른 글
[파이썬/백준 17142]연구소 3/ BFS (0) | 2021.04.07 |
---|---|
[python/leetcode]cheapest flights within k stops/dijkstra (0) | 2021.04.07 |
[python/leetcode]network delay time/dijkstra/heapq (0) | 2021.04.07 |
[python/leetcode]course schedule/tree/dfs (0) | 2021.04.07 |
파이썬 defaultdcit 런타임에러 RuntimeError: dictionary changed size during iteration (0) | 2021.04.05 |