日期:2014-05-20 浏览次数:20972 次
decimal Salary(Employee e) { decimal s = e.salary; if (e.EmployeeCollection != null) { foreach (Employee x in e.EmployeeCollection) { s += Salary(x); } } return s; }
------解决方案--------------------
楼上的只计算了三层:本人、直接下属、直接下属的直接下属,第四层以后的都没有计算。
------解决方案--------------------
受8楼的启发,找到了不用递归的方法 TotalSalaryWithoutRecursion():
using System.Collections.Generic; class Employee { // 该员工本人的薪金 public decimal salary; // 该员工的直接下属的集合 public List<Employee> EmployeeCollection; // 该员工及其下属(直接和间接)的总薪金,递归的方法 public decimal TotalSalary() { decimal s = salary; if (EmployeeCollection != null) { foreach (Employee x in EmployeeCollection) { s += x.TotalSalary(); } } return s; } // 该员工及其下属(直接和间接)的总薪金,不用递归的方法 public decimal TotalSalaryWithoutRecursion() { decimal s = salary; for (List<Employee> ec = EmployeeCollection; ec != null && ec.Count > 0; ec = SubCollection(ec)) { foreach (Employee e in ec) { s += e.salary; } } return s; } // 返回员工集合 ec 中每个员工的直接下属组成的集合 private List<Employee> SubCollection(List<Employee> ec) { List<Employee> list = new List<Employee>(); foreach (Employee e in ec) { if (e.EmployeeCollection != null) list.AddRange(e.EmployeeCollection); } return list; } }
------解决方案--------------------
每天回帖即可获得10分可用分!小技巧:教您如何更快获得可用分
------解决方案--------------------
..
------解决方案--------------------
lg
------解决方案--------------------
学习了,很不错
------解决方案--------------------
好东东,谢谢楼主
------解决方案--------------------
每天回帖即可获得10分可用分!小技巧:教您如何更快获得可用分
------解决方案--------------------
学习了
------解决方案--------------------
写一种 队列的方法
大概考这个呗
using System;
using System.Collections.Generic;
Queue<string> employeers = new Queue<string>();
public decimal totalSalary(employee person)
{
decimal totalSalary=0;
employeers.enqueue(person);
while(employeers.count>0)
{
totalSalary+=employeers.peek().salary;
if(employeers.peek().EmployeeCollection!=null)
{
foreach(employee e in employeers.peek().EmployeeCollection)
{
employeers.enqueue(e);
}
}
employeers.dequeue(employeers.peek());