0/1 knapsack problem
Problem statement
Given n items with size Ai and value Vi, and a backpack with size m. What's the maximum value can you put into the backpack?
Solution
0/1 knapsack problem is a classical dynamic programming model. There is a knapsack with the capacity of m, you should find the maximum volume can be filled in.
Still, we need:
- DP memory and the representation
- The initialization of DP memory
- DP formula
- Return value.
DP memory and the representation
Suppose, size is the number of elements in A.
A two dimension array: dp[size + 1][m + 1]
- dp[i][j]: means the maximum volume formed by first i elements whose volume is at most j.
The key word is the first and at most.
- The first means there are i + 1 elements.
- At most means the total volume can not exceed j.
Initialization
For a two dimension DP memory, normally, we should initialize the first row and column, and start from i = 1 and j = 1. The initialization comes from general knowledge.
- dp[0][i]: first 0 elements can form at most i volume. Obviously, the initialization is 0 since we can get nothing if there is no elements.
- dp[i][0]: first i elements can form at most 0 volume. Obviously, the initialization is 0 since we can get 0 volume by any elements.
DP formula
For current element A[i], we need to know what is the maximum volume can get if we add it into the backpack.
- dp[i][j] = dp[i - 1][j] if A[i - 1] is greater than j
- dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - A[i - 1]]) if j >= A[i - 1], we find the maximum value.
Return value.
Just return dp[size][m]
Time complexity is O(size * m)
class Solution { public: /** * @param m: An integer m denotes the size of a backpack * @param A & V: Given n items with size A[i] and value V[i] * @return: The maximum value */ int backPackII(int m, vector<int> A, vector<int> V) { // write your code here // write your code here int size = A.size(); //vector<vector<int>> dp(size + 1, vector<int>(m + 1, 0)); int dp[size + 1][m + 1] = {}; for(int i = 1; i <= size; i++){ for(int j = 1; j <= m; j++){ dp[i][j] = dp[i - 1][j]; if(j >= A[i - 1]){ dp[i][j] = max(dp[i][j], V[i - 1] + dp[i - 1][j - A[i - 1]]); } } } return dp[size][m]; } };