背包问题深度解析

using System;

class Program
{
    static void Main()
    {
        int[] weights = { 2, 3, 4 };
        int[] values = { 3, 4, 5 };
        int capacity = 5;

        int maxValue = Knapsack(weights, values, capacity);
        Console.WriteLine("最大总价值为: " + maxValue);
    }

    static int Knapsack(int[] weights, int[] values, int capacity)
    {
        int n = weights.Length;
        int[,] dp = new int[n + 1, capacity + 1];

        // 初始化动态规划表
        for (int i = 0; i <= n; i++)
        {
            for (int w = 0; w <= capacity; w++)
            {
                if (i == 0 || w == 0)
                    dp[i, w] = 0;
                else if (weights[i - 1] <= w)
                    dp[i, w] = Math.Max(values[i - 1] + dp[i - 1, w - weights[i - 1]], dp[i - 1, w]);
                else
                    dp[i, w] = dp[i - 1, w];
            }
      

你可能感兴趣的:(算法,代理模式)