DFS:690. Employee Importance
程序员文章站
2024-03-22 12:24:58
...
这道题是说,每一个员工有三个属性:id,重要性importance,直系下属id[]。题目给出每个员工的信息,并且给出一个id,求出这个员工的所有下属。
/*
// Employee info
class 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;
}
};