题目:
分析:
各个元素之间存在着1父对多子的关系,这显然是一个树的结构,自然想到采用深度优先或者广度优先的方式来做,
笔者采用深度优先的方式,
1)首先要根据传入的参数id找到该元素在vector中的位置,就是找到指向该元素的指针。
Employee* currentemployee=new Employee();
if(employees.size()<=0){
return 0;
}
else{
for(auto i:employees){
//这里auto i:v
//v是容器或者流类型,i的数据类型是v中元素的类型,这里i是Employee类型的数据,遍历该容器中的每个元素
if(i->id==id){
currentemployee=i; //找到id一样的元素,将指针保存为currentemployee
break;//跳出循环
}
}
}
2)采用递归的方式,求每个元素的子树的重要性之和
sumimportance+=currentemployee->importance;
for(auto a:currentemployee->subordinates){
sumimportance+=getImportance(employees,a);
}
return sumimportance;
整体代码:
/*
// 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;
};
*/
#include <vector>
using std::vector;
class Solution {
public:
int getImportance(vector<Employee*> employees, int id) {
int sumimportance=0;
Employee* currentemployee=new Employee();
if(employees.size()<=0){
return 0;
}
else{
for(auto i:employees){
if(i->id==id){
currentemployee=i;
break;
}
}
}
sumimportance+=currentemployee->importance;
for(auto a:currentemployee->subordinates){
sumimportance+=getImportance(employees,a);
}
return sumimportance;
}
};
运行结果: