0-1 knapsack problem (0-1 knapsack problem) is this: a thief who is robbing a shop found n goods, the first commodity value VI, the type WI pound, VI and WI are all integers. The thief wanted to take away the highest-value goods, but his backpack could hold up to a W-pound commodity, and W was an integer. What kind of goods should he take? (We call
The problem is 0-1 knapsack problem, because for each commodity, the thief either takes it completely away or leaves it behind; he can't just take a part of a product, or take a product away multiple times. )
The students who have contacted the dynamic planning must have heard the 0-1 knapsack problem. The core of dynamic programming is state and state transition equations.
D[I][J] indicates that the backpack capacity is J and the number of items is I. For the first item, either take it or do not take it. Take the words, get value VI, consume backpack capacity WI, at this time the problem is converted to D[I-1][J-WI].
If not taken, the problem is converted directly to D[i-1][j]. For maximum value, d[i, j] = max (D[i-1][j-wi] + VI, D[I-1][J]).
The code is implemented as follows:
0-1 knapsack problem