【问题标题】:specific Knapsack Algorithm [duplicate]特定的背包算法
【发布时间】:2016-11-08 07:08:50
【问题描述】:

我对解决特定的背包算法问题有疑问。有没有人给我一些提示或帮助我?我通过蛮力方法解决了它,但执行时间很长(我检查了所有可能的组合并采取了最佳解决方案 - 它有效)。我需要通过动态编程或贪心算法(但通过 DP 更好)来解决它。我读了很多,但找不到解决方案;/这是一项艰苦的练习。 HERE IS description of my exercise

HERE ARE TESTS FOR THIS EXERCISE

【问题讨论】:

  • 将您的描述文本和测试作为文本发布在您的问题中。但即使有了这些,您也需要将您要问的内容缩小到一个特定的问题:“我该怎么做”并不具体。
  • 请发布您的代码、您面临的错误以及您面临的具体问题。如需更通用的指南,请查看my answer

标签: java algorithm knapsack-problem


【解决方案1】:

互联网上有一些很好的教程,可以彻底解释背包问题。

更具体地说,我会推荐this specific one,其中完整地解释了问题和 DP 方法,包括三种不同语言(包括 Java)的解决方案。

// A Dynamic Programming based solution for 0-1 Knapsack problem
class Knapsack
{
    // A utility function that returns maximum of two integers
    static int max(int a, int b) { return (a > b)? a : b; }

   // Returns the maximum value that can be put in a knapsack of capacity W
    static int knapSack(int W, int wt[], int val[], int n)
    {
         int i, w;
     int K[][] = new int[n+1][W+1];

     // Build table K[][] in bottom up manner
     for (i = 0; i <= n; i++)
     {
         for (w = 0; w <= W; w++)
         {
             if (i==0 || w==0)
                  K[i][w] = 0;
             else if (wt[i-1] <= w)
                   K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]],  K[i-1][w]);
             else
                   K[i][w] = K[i-1][w];
         }
      }

      return K[n][W];
    }

    // Driver program to test above function
    public static void main(String args[])
    {
        int val[] = new int[]{60, 100, 120};
        int wt[] = new int[]{10, 20, 30};
        int  W = 50;
        int n = val.length;
        System.out.println(knapSack(W, wt, val, n));
    }
}
/*This code is contributed by Rajat Mishra */

来源:GeeksForGeeks

【讨论】:

  • 伙计,我读到了。我创建了一个表 N 个项目/W 个权重,但现在应该做什么?我有所有组合,但是当我按此表上的最后一个索引时如何找到最佳解决方案对我没有帮助;s
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-17
  • 2023-03-11
相关资源
最近更新 更多