Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
employee-importance.cpp 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2017-09-30 23:24 +08:00 . Create employee-importance.cpp
// Time: O(n)
// Space: O(h)
/*
// 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) {
return dfs(employees, id);
}
private:
int dfs(const vector<Employee*>& employees, const int id) {
if (!employees[id - 1]) {
return 0;
}
auto result = employees[id - 1]->importance;
for (const auto& id : employees[id - 1]->subordinates) {
result += getImportance(employees, id);
}
return result;
}
};
// Time: O(n)
// Space: O(w), w is the max number of nodes in the levels of the tree
class Solution2 {
public:
int getImportance(vector<Employee*> employees, int id) {
auto result = 0;
queue<int> q;
q.emplace(id);
while (!q.empty()) {
const auto curr = q.front(); q.pop();
const auto& employee = employees[curr - 1];
result += employee->importance;
for (const auto& id : employee->subordinates) {
q.emplace(id);
}
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助