题目地址:
https://leetcode.com/problems/employee-importance/
给定一个Employee类,成员变量包括其id,importance(两个变量都是整数),还有一个其下属的id列表。给定一个Employee的id,求其自己与其所有直接和间接下属的importance总和。
法1:DFS。直接用其自己的importance累加其下属的importance即可,下属的importance可以递归求解。代码如下:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> map = new HashMap<>();
for (Employee employee : employees) {
map.put(employee.id, employee);
}
return dfs(map.get(id), map);
}
private int dfs(Employee emp, Map<Integer, Employee> map) {
int sum = emp.importance;
for (int subId : emp.subordinates) {
sum += dfs(map.get(subId), map);
}
return sum;
}
}
class Employee {
public int id;
public int importance;
public List<Integer> subordinates;
}
时空复杂度 O ( n ) O(n) O(n)。
法2:BFS。等同于多叉树搜索。代码如下:
import java.util.*;
public class Solution {
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> map = new HashMap<>();
for (Employee employee : employees) {
map.put(employee.id, employee);
}
int res = 0;
Queue<Employee> queue = new ArrayDeque<>();
queue.offer(map.get(id));
while (!queue.isEmpty()) {
Employee cur = queue.poll();
res += cur.importance;
for (int subId : cur.subordinates) {
queue.offer(map.get(subId));
}
}
return res;
}
}
时空复杂度一样。