欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【Leetcode】690. Employee Importance

程序员文章站 2024-03-22 12:21:28
...

【Leetcode】690. Employee Importance

# 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 Solution1:
    def getImportance(self, employees, id):
        """
        use dict , key is id , value is employee object, use id to locate an employee
        and use DFS to get all subordinates
        """
        dictionary = {}
        for employee in employees:
            dictionary[employee.id] = employee
        result = 0
        from collections import  deque
        queue = deque()
        queue.append(dictionary[id])
        while(len(queue)):
            top = queue.popleft()
            result += top.importance
            for sub in top.subordinates:
                queue.append(dictionary[sub])
        return result

class Solution2:
    """
    make code more concise
    """
    def getImportance(self, employees, id):
        dictionary = {employee.id:employee for employee in employees}
        def dfs(id):
            sub_importance = sum([dfs(sub_id) for sub_id in dictionary[id].subordinates])
            return sub_importance + dictionary[id].importance
        return dfs(id)

class Solution3:
    """
    make code more concise
    """
    def getImportance(self, employees, id):
        dictionary = {employee.id: employee for employee in employees}
        dfs = lambda id: sum([dfs(sub_id) for sub_id in dictionary[id].subordinates]) + dictionary[id].importance
        return dfs(id)