01 Backpack is a type of dynamic programming its main forms are:
1, all types of goods each type only one
2, only one at a time and the items can not be divided
3, only take or not take (so call 01 backpack, is only these two cases)
4, under the premise of the knapsack capacity dissatisfaction, as much as possible to load the maximum value of goods
The capacity of the backpack is V, the weight of the article I is weigh[i] corresponds to the value of price[i]; The maximum value of a backpack with a capacity of J (the maximum size of a backpack) is dp[j]
n is the total number of items, we start with the 1th data, then this item weighs weigh[1], then we put all the bags greater than weigh[1] into the 1th item (i.e. from DP[V] to
DP[WEIGH[1]]) at this time all backpacks larger than weigh[1] weight are loaded into the first item.
Next we loaded the 2nd item, and we were going to load a second item for all the backpacks that were larger than weigh[2], but some of the backpacks had been loaded when the first item was loaded.
The first item, how to do it? There are several situations:
1. If the capacity is insufficient to load the second item after loading the first item and the value of the first item is greater than the second piece, the second piece is not loaded
2. If the remaining capacity is insufficient to load the second item after loading the first item and the value of the first item enters the second piece, the second item is loaded to take out the first piece (of course in the program
Can be directly overwritten as the first item removed)
3. If the capacity of the first item is sufficient to fit the second item, two items will be loaded into the backpack together.
Code implementation:
And so on
Big God don't squirt
Dynamic planning 01 Backpack Records