今天在社区看到某个算法问题,其中有位朋友提出了背包问题的算法,特把他的方法贴在这里收藏一下:
1 namespace Program
2 {
3 public class Package
4 {
5 public double[] goods = new double[] { 1, 1.1, 2, 3, 4 };
6
7 /// <summary>
8 /// 用递归算出
9 /// </summary>
10 /// <param name="puts">目前放入背包的数</param>
11 /// <param name="unPuts">可放入背包的数</param>
12 /// <param name="sum">背包还剩的容量</param>
13 public void ShowComposes(List<double> puts,double[] unPuts, double sum)
14 {
15 //输出当前放入背包符合条件的所有数
16 bool exist = false;
17 foreach (double d in puts)
18 {
19 System.Console.Write(d+ " ");
20 exist = true;
21 }
22 if(exist)
23 System.Console.WriteLine();
24
25 //在可放入背包的数字中,选择可放的数并放进背包
26 foreach (double d in unPuts)
27 {
28 if (d < sum)
29 {
30 List<double> newPuts = puts.ToList<double>();
31 newPuts.Add(d);
32 ShowComposes(newPuts, goods, sum - d);
33 }
34 }
35 }
36
37 static void Main(string[] args)
38 {
39 Package p = new Package();
40 p.ShowComposes(new List<double>(), p.goods, 6);
41 }
42 }
43 }
44
2 {
3 public class Package
4 {
5 public double[] goods = new double[] { 1, 1.1, 2, 3, 4 };
6
7 /// <summary>
8 /// 用递归算出
9 /// </summary>
10 /// <param name="puts">目前放入背包的数</param>
11 /// <param name="unPuts">可放入背包的数</param>
12 /// <param name="sum">背包还剩的容量</param>
13 public void ShowComposes(List<double> puts,double[] unPuts, double sum)
14 {
15 //输出当前放入背包符合条件的所有数
16 bool exist = false;
17 foreach (double d in puts)
18 {
19 System.Console.Write(d+ " ");
20 exist = true;
21 }
22 if(exist)
23 System.Console.WriteLine();
24
25 //在可放入背包的数字中,选择可放的数并放进背包
26 foreach (double d in unPuts)
27 {
28 if (d < sum)
29 {
30 List<double> newPuts = puts.ToList<double>();
31 newPuts.Add(d);
32 ShowComposes(newPuts, goods, sum - d);
33 }
34 }
35 }
36
37 static void Main(string[] args)
38 {
39 Package p = new Package();
40 p.ShowComposes(new List<double>(), p.goods, 6);
41 }
42 }
43 }
44
原帖地址:http://topic.csdn.net/u/20080827/13/3fbba373-8882-4d22-a0f2-2188b0ba2ef6.html