Recently, I wrote this article in reviewing algorithm knowledge to help myself understand memory

01 Knapsack problem

01 The goal of the knapsack problem is to achieve the maximum item value within a fixed capacity limit
01 Pair of meanings: Unable to divide items
01 The knapsack problem is usually solved in two ways: violent backtracking and dynamic programming

Brute Force

The backtracking method checks that the time complexity of all combinations is exponential, and it is easy to break the time table, so I won't look at it here.

dynamic programming

The core of dynamic programming is to find sub-problems, in this question we first look for sub-problems

find subproblems

Assume the maximum weight of the backpack is 5
Item information is as follows

weight value
item 1 4 7
item 2 3 5
item 3 5 6
item 4 3 3
item 5 2 8

Each position of the dp table stores such a large backpack. What is the maximum profit? Let's consider first, if there is only item 1, if it can't fit, the profit is 0
If our backpack can fit, then the maximum profit is 7, we update the first line

0 1 2 3 4 5
item 1 0 0 0 0 7 7
item 2
item 3
item 4
item 5

The solution to the global problem is obtained by solving the sub-problems

Now consider item 2, if it can't fit, the profit is the result of the same position on the previous line

If it can be loaded: Judging the result of the same position in the previous line, the value of this item plus the weight of the item after removing the weight of the item in the previous line.

 dp[i][j] = max(dp[i-1][j], dp[i-1][j-weight[i]]+values[i])
0 1 2 3 4 5
item 1 0 0 (4 - weight of item 2) 0 0 7 7
item 2 0 0 0 5 max(7, (5 + 0 ))
item 3
item 4
item 5

iterate

0 1 2 3 4 5
item 1 0 0 0 0 7 7
item 2 0 0 0 5 7 7
item 3 0 0 0 5 7 7
item 4 0 0 0 5 7 7
item 5 0 0 8 8 8 13

The final result is 13

The complete Python code is as follows

 #
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 计算01背包问题的结果
# @param V int整型 背包的体积
# @param n int整型 物品的个数
# @param vw int整型二维数组 第一维度为n,第二维度为2的二维数组,vw[i][0],vw[i][1]分别描述i+1个物品的vi,wi
# @return int整型
#
class Solution:
    def knapsack(self, V: int, n: int, vw: List[List[int]]) -> int:
        # write code here
        dp = [[0] * (V + 1) for _ in range(n)]
        for i in range(V + 1):
            if i >= vw[0][0]:
                dp[0][i] = vw[0][1]
        for i in range(1, n):
            for j in range(V + 1):
                if j < vw[i][0]:
                    dp[i][j] = dp[i-1][j]
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i-1][j-vw[i][0]]+vw[i][1])
        return dp[n-1][V]

Hydrogen
2.5k 声望73 粉丝

Write code for fun.