回溯算法之0-1背包问题

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

namespace SeqListSort
{
    /// <summary>
    /// <ather>
    /// lihonglin
    /// </ather>
    /// <content>
    /// 问题描述:有n件物品和一个容量为c的背包。第i件物品的价值是v[i],重量是w[i]。求解将哪些物品装入
    /// 背包可使价值总和最大。在装入背包时,每种物品i只有两种选择,装入或者不装入,既不能装入多次,
    /// 也不能只装入一部分。因此,此问题称为0-1背包问题
    /// 背包问题可看做是一种回溯: 每个包是一个节点, 节点共有2个候选值0、1 。 0代表不放人背包中, 1代表放入背包中。
    /// </content>
    /// </summary>
    class Knapsack
    {
        static int n = 5;//物品数量
        static int c = 10;//背包容量
        static int[] weight = new int[] { 2, 2, 6, 5, 5 };// 各个物品的重量
        static int[] value = new int[] { 6, 3, 5, 4, 6 };//各个物品的价值

        static int max = 0; //max:记录最大价值
        static int[] a = new int[n];//数组存放当前解 各物品选取情况
        //a[i]=0表示不选第i件物品,a[i]=1表示选第i件物品


        static void CheckMax()
        {
            int i = 0;
            int curWeight = 0;//当前物品的重量
            int curValue = 0;//当前物品的价值
            for (i = 0; i < n; i++)
            {
                if (a[i] == 1) //如果选取了该物品
                {
                    curWeight += weight[i]; //累加重量
                    curValue += value[i]; //累加价值
                }
            }
            if (curWeight <= c) //若为可行解
                if (curValue > max) //且价值大于max
                {
                    max = curValue; //替换max
                }
        }

        public static void Search(int m)
        {

            if (m >= n)
                CheckMax(); //检查当前解是否是可行解,若是则把它的价值与max比较
            else
            {

                a[m] = 1; //选则第m件物品
                Search(m + 1); //递归搜索下一件物品
                a[m] = 0; //不选第m件物品
                Search(m + 1); //递归搜索下一件物品
            }
        }

        public static void PrintResult()
        {
            Console.WriteLine("最大价值 " + max);
        }
    }
}
原文地址:https://www.cnblogs.com/lihonglin2016/p/4307863.html