In the brush of the Huawei Machine test online programming, encountered a problem similar to 01 knapsack problems, a combination of some information, write some of their own understanding
01 knapsack problem is the problem of finding the maximum value under limited weighing capacity
Assume several parameters:
W[i]: The weight of the article I;
P[i]: The value of the first item;
V[I][J]: Indicates the maximum value of the total weight of J in the first I items;
V[i-1][j-w[i]]: Indicates the maximum value of the load-bearing capacity of the first i-1 items after the addition of the article I;
We analyze: Before adding the article I item, we have to consider want to add in, do not add in, then is v[i][j]=v[i-1][j], if add in, then V[i][j]=v[i-1][j-w[i]]+p[i]
Specific examples such as
There are five items numbered a,b,c,d,e, their weight is 2,2,6,5,4, their value is 6,3,5,4,6, now give you a load-bearing of 10 of the backpack, how to make the backpack loaded items have the greatest value of the sum?
The first thing to make clear is that the table is bottom-up, from left to right.
For the sake of convenience, using E2 cell to represent e Row 2 column cell, the meaning of this cell is used to indicate that only the item E, there is a load bearing 2 of the backpack, then the maximum value of this backpack is 0, because the weight of the E-item is 4, the backpack can not be loaded.
For D2 cell, it means that only the item e,d, the load-bearing 2 backpack, the maximum value that can be loaded, is still 0, because the item e,d is not the backpack can be installed.
In the same vein, c2=0,b2=3,a2=6.
Then the state transition equation can be expressed as:
V[i][j]=max{v[i-1][j],v[i-1][j-w[i]]+p[i]}
Then the code is implemented as follows:
Import java.util.*;p Ublic class Main {public static void main (string[] args) {//TODO auto-generated method Stubint Weight = 10;int n = 3;int[] W = {3,4,5};int[] p = {4,5,6}; System.out.println (Getmaxweight (W, p, weight, n));} public static int Getmaxweight (int[] W, int[] p, int weight, int n) {int[][] value = new Int[n+1][weight+1];for (int i = 1;i <=n;i++) {for (int j = 1;j<=weight;j++) {//When the item is weight j, if the weight of Part I (W[i-1]) is less than the weight J, C[i][j] is one of the following two cases://(1) Item I is not put in the backpack, So C[i][j] is the value of the c[i-1][j]//(2) item I into the backpack, the backpack remaining weight is j-w[i-1], so c[i][j] "c[i-1][j-w[i-1") value plus the value of the current item I if (W[I-1]<=J) { Value[i][j]=math.max (Value[i-1][j], value[i-1][j-w[i-1]]+p[i-1]);}} return value[n][weight];}}
01 Knapsack problem Java Implementation