特定的背包算法

时间:2016-11-07 21:50:30

标签: java algorithm knapsack-problem

我有解决特定背包算法问题的问题。有人给我一些提示或帮助我吗?我用Brute Force方法解决了它,但执行时间很长(我检查了所有可能的组合并采取了最佳解决方案 - 它的工作原理)。我需要通过动态编程或贪婪算法来解决它(但DP更好)。我读了很多,但我无法找到解决方案;这是很难锻炼的。 HERE IS description of my exercise

HERE ARE TESTS FOR THIS EXERCISE

1 个答案:

答案 0 :(得分: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