好几种写法,这里贴几个出来
第一种:暴力解法,除去递归栈,空间复杂度O(1)。时间复杂度略高
1 /* 2 // Employee info 3 class Employee { 4 public: 5 // It's the unique ID of each node. 6 // unique id of this employee 7 int id; 8 // the importance value of this employee 9 int importance; 10 // the id of direct subordinates 11 vector<int> subordinates; 12 }; 13 */ 14 15 static int wing=[]() 16 { 17 std::ios::sync_with_stdio(false); 18 cin.tie(NULL); 19 return 0; 20 }(); 21 22 class Solution 23 { 24 public: 25 int getImportance(vector<Employee*> employees, int id) 26 { 27 return getsum(employees,id); 28 } 29 30 int getsum(vector<Employee*>employees,int id) 31 { 32 Employee * cur; 33 int cursum=0; 34 for(auto p:employees) 35 { 36 if(p->id==id) 37 { 38 cur=p; 39 cursum+=p->importance; 40 break; 41 } 42 } 43 if(!(cur->subordinates.empty())) 44 { 45 for(auto subid:cur->subordinates) 46 cursum+=getsum(employees,subid); 47 } 48 return cursum; 49 } 50 };
第二种:用关联容器,速度快一丢丢,但是空间复杂度高一丢丢
1 /* 2 // Employee info 3 class Employee { 4 public: 5 // It's the unique ID of each node. 6 // unique id of this employee 7 int id; 8 // the importance value of this employee 9 int importance; 10 // the id of direct subordinates 11 vector<int> subordinates; 12 }; 13 */ 14 15 static int wing=[]() 16 { 17 std::ios::sync_with_stdio(false); 18 cin.tie(NULL); 19 return 0; 20 }(); 21 22 class Solution 23 { 24 public: 25 int getImportance(vector<Employee*> employees, int id) 26 { 27 unordered_map<int,Employee*> iemap; 28 for(auto i:employees) 29 iemap[i->id]=i; 30 return getsum(iemap,id); 31 } 32 33 int getsum(unordered_map<int,Employee*> & emap,int id) 34 { 35 int cursum=emap[id]->importance; 36 for(auto e:emap[id]->subordinates) 37 cursum+=getsum(emap,e); 38 return cursum; 39 } 40 };
第三种,用数组,空间复杂度比map高些,但是速度更快
1 /* 2 // Employee info 3 class Employee { 4 public: 5 // It's the unique ID of each node. 6 // unique id of this employee 7 int id; 8 // the importance value of this employee 9 int importance; 10 // the id of direct subordinates 11 vector<int> subordinates; 12 }; 13 */ 14 15 static int wing=[]() 16 { 17 std::ios::sync_with_stdio(false); 18 cin.tie(NULL); 19 return 0; 20 }(); 21 22 class Solution 23 { 24 public: 25 int getImportance(vector<Employee*> employees, int id) 26 { 27 Employee* ptr[2000]={nullptr}; 28 for(auto p:employees) 29 ptr[p->id]=p; 30 return getsum(ptr,id); 31 } 32 33 int getsum(Employee* (&ptr)[2000],int id) 34 { 35 int cursum=ptr[id]->importance; 36 for(auto e:ptr[id]->subordinates) 37 cursum+=getsum(ptr,e); 38 return cursum; 39 } 40 };
三种方法都可以,都用了递归