There are n items, the first item (i = 1,2,3...N) is the value of VI, the weight is WI, we have a load-bearing for m backpack, we choose some items into the backpack, each can only put one, obviously put the total weight of the backpack not more than M. We ask to choose the total value of the item is the largest, please ask how to choose. Here we assume that all occurrences of the number are positive integers.
If the knapsack problem is not carefully understood, the first way of thinking should be greedy.
For example, first to the item of the value of the order, first select the more expensive.
However for data:
n = 3, M = 3
v = (2,2,3)
W = (all in all)
According to the strategy of selecting valuables first, we will select the one with the value of 3, and the backpack is full, but if we select the first two items, the total value can reach 4.
If you sort by price/performance:
For data
n = 3, M = 7
v = (2,3,4)
W = (3,4,5)
In this way, because 2/3 < 3/4 < 4/5, we first select the third item, but after selecting it, something else will not fit. The total value is 4, but if we choose the top two items we can get the total value of 5.
The reason for this phenomenon is that the greedy principle is: the optimal solution of the whole is deduced through the optimal solution of each step, however, for knapsack problem, because the optimal solution of each step or not is determined by the whole, namely "dynamic". Therefore, knapsack problem becomes a classic dynamic programming problem.
And look at some knapsack problem.
A traveler has a pack of up to M kg, and then n heavy items, which weigh and value w[i],c[i], asking the traveler the maximum value they can get
This is a question of greed, because we can always choose the cost-effective to fill up, so whether or not greed depends on whether each item is only taken part of.
And the knapsack problem has derived a lot of deformation, dynamic planning methods are not the same, so need more practice to master this question.
Reference article:
51NOD
Baidu knows
Baidu Library