因为有的问题,用动态规划解决起来,比较耗费性能,而用贪心算法,虽然不能得到最优解,但也能得到次优解,与动态规划比起来更加简单节约性能。
通常最早结束的活动a1它一定在最优解中,根据这一点来实现贪心算法。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 贪心算法_递归代码实现 { class Program { static void Main(string[] args) { List<int> result = Methord(0, 11, 0,24); foreach (int temp in result) { Console.WriteLine(temp); } Console.ReadKey(); List<int> result2 = Methord2(0, 11, 0, 0); foreach (int item in result2) { Console.WriteLine(item); } Console.ReadKey(); } static int[] s = { 0, 1, 3, 0, 5, 3, 5, 6, 8, 8, 2, 12, 24 }; static int[] f = { 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 24 }; // static List<int> result = new List<int>(); /// <summary> /// /// </summary> /// <param name="startActiveNum"></param>开始活动的编号 0 /// <param name="endActiveNum"></param>结束活动的编号 n /// <param name="startTime"></param>开始活动的时间 上一个活动 0 /// <param name="endTime"></param>结束活动的时间 总活动时间 /// <returns></returns> static List<int> Methord(int startActiveNum,int endActiveNum,int startTime,int endTime) { if(startActiveNum>endActiveNum) { return new List<int>(); } int temp = 0; //从下一个活动开始 for(int number = startActiveNum;number<=endActiveNum;number++) { if(s[number]>=startTime&&f[number]<=endTime) { // result.Add(number); temp = number; break; } } List<int> list = Methord(temp+1, endActiveNum, f[temp],endTime); list.Add(temp); return list; } /// <summary> /// /// </summary> /// <param name="startActiveNum"></param>上一个活动那个的开始时间 /// <param name="endActiveNum"></param> 最后一个活动的编号通常是一个定值 /// <param name="startTime"></param> 上一个活动的开始时间 /// <param name="endTime"></param> 上一个活动的结束时间 /// <returns></returns> static List<int> Methord2(int startActiveNum, int endActiveNum, int startTime, int endTime) { if (startActiveNum > endActiveNum) { return new List<int>(); } int temp = 0; //从下一个活动开始 for (int number = startActiveNum; number <= endActiveNum; number++) { if (s[number] >= endTime) { // result.Add(number); temp = number; break; } } List<int> list = Methord2(temp + 1, endActiveNum, s[temp], f[temp]); list.Add(temp); return list; } } }