https://blog.csdn.net/qq_40788630/article/details/79503946
动态规划解决0/1背包问题的C#代码,迭代,下面的代码还没有使用动态规划
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Result a = p.maxValue(p.buildItem(), 150);
foreach (Item i in a.items)
{
Console.WriteLine(i);
}
Console.WriteLine(a.value);
Console.ReadKey();
}
List<Item> buildItem()
{
string[] names = { "AA", "B" };
int[] vals = { 50, 30};
int[] weights = { 130, 40 };
List<Item> items = new List<Item>();
for (int i = 0; i < names.Length; i++)
{
items.Add(new Item(names[i], vals[i], weights[i]));
}
return items;
}
//oraSet 备选的物品箱 leftRoom剩余的空间大小
Result maxValue(List<Item> oraSet, int leftRoom)
{
if (oraSet.Count == 0 || leftRoom == 0)//退出条件,备选箱没东西了或者背包满了
{
return new Result(0, new List<Item>());
}
else if (oraSet[0].getWeight() > leftRoom)//如果物品体积太大,直接丢弃
{
List<Item> a = new List<Item>();
for (int i = 1; i < oraSet.Count; i++)
{
a.Add(oraSet[i]);
}
return maxValue(a, leftRoom);
}
else
{
Item nextItem = oraSet[0];//取出第一个
List<Item> a = new List<Item>();
for (int i = 1; i < oraSet.Count; i++)
{
a.Add(oraSet[i]);
}
Result l = maxValue(a, leftRoom - (int)nextItem.getWeight());//把箱子剩下,把剩余空间装满的结果返回。注意,传入的参数:是剩下的物品
int left = l.value + nextItem.getValue();//如果要这个物品,得到总价值
Result r = maxValue(a, leftRoom);//如果丢弃此物品,得到的总价值.注意,传入的参数:是剩下的物品
if (left > r.value)//根据价值大小选择要哪些物品
{
l.items.Add(nextItem);//说明还要此物品,把此物品返回
return new Result(left, l.items);//结果包含此物品
}
else
{
return new Result(r.value, r.items);//丢弃此物品,把结果返回
}
}
}
}
public class Result
{
public int value;
public List<Item> items = new List<Item>();
public Result(int v, List<Item> its)
{
this.value = v;
this.items = its;
}
}
public class Item
{
string name;
int value;
int weight;
public Item(string n, int v, int w)
{
this.name = n;
this.value = v;
this.weight = w;
}
public string getName()
{
return this.name;
}
public int getValue()
{
return this.value;
}
public int getWeight()
{
return this.weight;
}
public override string ToString()
{
string result = " < " + this.name + " , " + this.value + " , " + this.weight + ">";
return result;
}
}