编辑代码

using System;
using System.Collections.Generic;

class goods
{
    public string name;
    public int value;
    public int weight;

    public goods(string name, int value, int weight)
    {
        this.name = name;
        this.value = value;
        this.weight = weight;
    }
}


namespace C1
{
    class Program
    {
        static void Main(string[] args)
        {
            
            List<goods> list = new List<goods>();
            list.Add(new goods("吉他",1, 1500));
            list.Add(new goods("音响",4, 3000));
            list.Add(new goods("笔记本电脑",3, 2000));
            list.Add(new goods("IPhone",1, 2000));

            // 背包容量
            int capacity = 5;

            int[,] result = new int[list.Count+1, capacity+1];

            for (int i = 0; i <= capacity; i++)
            {
                result[0, i] = 0;
            }

            for (int i = 1; i <= list.Count; i++)
            {
                for (int j = 0; j <= capacity; j++)
                {
                    if (list[i-1].value <= j)   // 首先要保证当前容量能够容下该物品
                    {
                        result[i, j] = Math.Max(list[i - 1].weight + result[i - 1, j - list[i - 1].value], result[i - 1, j]);    // 状态转移方程
                    }
                    else
                    {
                        result[i, j] = result[i - 1, j];
                    }
                }
            }


            Console.WriteLine($"可以获得最大值:{result[list.Count,capacity]}");
        }  

    }
}