DFS:690. Employee Importance

来源:互联网 发布:达芬奇 去闪烁 mac 编辑:程序博客网 时间:2024/05/21 21:03

这道题是说,每一个员工有三个属性:id,重要性importance,直系下属id[]。题目给出每个员工的信息,并且给出一个id,求出这个员工的所有下属。

/*// Employee infoclass Employee {public:    // It's the unique ID of each node.    // unique id of this employee    int id;    // the importance value of this employee    int importance;    // the id of direct subordinates    vector<int> subordinates;};*/class Solution {public:    int getImportance(vector<Employee*> employees, int id) {        unordered_map<int, Employee*> m;        for(auto e : employees)        {            m[e->id] = e;        }        int sum = 0;        return dfs(m, id, sum);    }    int dfs(unordered_map<int, Employee*>& m, int id, int& sum)    {        sum += m[id]->importance;        for(auto i : m[id]->subordinates)        {            dfs(m, i, sum);        }        return sum;    }};

讨论区:

class Solution {public:    int getImportance(vector<Employee*> employees, int id) {                unordered_map<int, Employee*> map;                for(const auto element : employees){                        map[element->id] = element;        }                return help(map, id);    }        int help(unordered_map<int, Employee*>& map, const int id){                auto sum = map[id]->importance;                for(const auto element : map[id]->subordinates){                        sum += help(map, element);        }                return sum;    }};


原创粉丝点击