c#背包问题代码

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //货物重量和价值
            int[,] a;
            //背包承重
            int w;
            ////测试数据1,答案是133
            //a = new int[,] { { 77, 22, 29, 50, 99 }, { 92, 22, 87, 46, 90 } };
            //w = 100;
            ////测试数据2,答案是334
            a = new int[,] { { 79,58,86,11,28,62,15,68 }, { 83,14,54,79,72,52,48,62 } };
            w = 200;
            int v;
            v = getmaxvalue(w, a, 0);
            Console.WriteLine($"最大价值为:{v}");
            Console.ReadKey();
        }
        //获得背包w,装货物o,从第flag件向后考虑,能得到的最大价值
        static int getmaxvalue(int w, int[,] o, int flag)
        {
            int v, t1, t2;
            //如果是最后一件货物
            if (flag == o.GetLength(1) - 1)
            {
                if (w >= o[0, flag])
                {
                    v = o[1, flag];
                }
                else
                {
                    v = 0;
                }
            }
            //如果装得下当前货物
            else if (w >= o[0, flag])
            {
                t1 = getmaxvalue(w - o[0, flag], o, flag + 1) + o[1, flag];
                t2 = getmaxvalue(w, o, flag + 1);
                v = max(t1, t2);
            }
            //装不下当前货物的情况
            else
            {
                v = getmaxvalue(w, o, flag + 1);
            }
            return v;
        }
        static int max(int a, int b)
        {
            return a > b ? a : b;
        }
    }
}
原文地址:https://www.cnblogs.com/wanjinliu/p/12960815.html