一开始写的很麻烦,是因为忘记了auto的使用,auto适合做这种数据结构比较复杂的题。使用auto一般要结合for迭代循环,即for(:)可以参考一篇博文 https://blog.youkuaiyun.com/u010141928/article/details/78671452
该题的题意多少有些模糊,其实是求不仅是直接下属的所有员工的weight的和,还有直接下属的员工的直接下属的员工。
class Solution {
public:
int sum=0;
void dfs(vector<Employee*> employees, int id)
{
for(auto temp : employees) //employees 是个保存Employee* 值的vector,所以auto的temp是Employee*类型
{
if(temp->id==id)
{
sum +=temp->importance;
if(!temp-> subordinates.empty())//加一个非空判断是很有必要的
{
for(auto sub_id : temp-> subordinates)//subordinates是个保存int类型(id)的vector,所以auto的sub_id是int类型
{
dfs(employees, sub_id);
}
}
}
}
}
int getImportance(vector<Employee*> employees, int id) {
dfs(employees, id);
return sum;
}