This is a creation in Article, where the information may have evolved or changed.
Very classical dynamic planning problems, specific ideas here is not listed, too much information on the web. If you want to understand it in detail, you can see the backpack nine.
Listed here, 01 backpacks, full backpack, partial backpack Golang realized.
01 Backpack
Given n items and a backpack with a capacity of C, the weight of item I is WI, its value is VI.
How do you choose which items are loaded into your backpack so that the total value of the items loaded into the backpack is the largest?
From left to right, fill in the form from top to bottom (example:5 means weight, 12 means value)
1.png
Code and comments
DP[I][J] = max (Dp[i-1][j], nums[i][1]+dp[i-1][j-nums[i][0]) think carefully about this line
Backpack.png
Full backpack
Given n items and a capacity of C backpack, the weight of the item I is WI, its value is VI, each item has an unlimited number of pieces, now to pack inside the contents, how to pack can make the contents of the backpack the most valuable?
First look at the picture:
This is a one-dimensional array, and each row represents the result of each traversal
2.png
Code and comment, understand the above one, this is also very good understanding
Backpack1.png
Partial backpack
Given n items and a capacity of C backpack, the weight of item I is WI, its value is VI, each item has ki pieces, now into the backpack inside loaded things, how can make the backpack in the value of the largest items?
A relatively simple but inefficient method: the article I of the Ki items into k pieces of different items, directly into the 01 knapsack problem. But less efficient.
Another idea: To apply an array to save the number of items I use, so as to control the quantity of items I, with the idea of a complete backpack to solve the problem
Code and comments
Backpack3.png
Traversal: DP represents the optimal value for each item that is traversed, and count indicates the number of items to be placed when the weight is n
Dp[0 0 0 0 0 8 8 8 8 8 16 16 16 16 16 16]
Count[0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 2]
Dp[0 0 0 0 3 8 8 8 8 11 16 16 16 16 19 19]
Count[0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1]
Dp[0 0 0 0 3 8 8 10 10 11 16 16 18 18 20 20]
Count[0 0 0 0 0 0 0 1 1 0 0 0 1 1 2 2]
Dp[0 0 3 3 6 8 9 11 11 14 16 17 19 19 22 22]
Count[0 0 1 1 2 0 3 1 1 2 0 3 1 1 2 2]
Dp[0 0 3 3 6 8 9 11 11 14 16 17 19 19 22 22]
Count[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Summarize:
Basically, the problem of knapsack problems will eventually translate into 01 knapsack problem, the core code is based on a formula:
F[i][v]=max{f[i-1][v],f[i-1][v-c[i]]+w[i]}
The code also has a lot of room for optimization. Just keep a record of your learning process.