# 01背包问题笔记：4个关键点以及Python实现

Andy

01背包问题：

• 理解背包问题的描述，如图，将有价值和重量的物体，放入固定大小的背包。算出最大价值

• 理解01背包问题的表格，假设有a,b,c,d,e五个物体，其重量分别为2,2,6,5,4，价值分别为6,3,5,4,6，当背包可容纳的重量从1变化到10时，最大的价值

• 理解最大价值的公式：

``optimal[i][j]=max(optimal[i-1][j],optimal[i-1][j-weight[i-1]]+value[i-1])``
• 理解一维数组求最大价值

``optimal[j]=max(optimal[j],optimal[j-weight[i]]+value[i])``
1. Python的实现
``````# 0-1 Knapsack Problem 0-1背包问题

weight = [4, 5, 6, 2, 2]
value = [6, 4, 5, 3, 6]
CAPACITY = 8
NUM = len(weight)

def knapsack_MATRIX():
optimal = [[0 for x in range(CAPACITY + 1)] for x in range(NUM + 1)]
for i in range(1, NUM + 1):
for j in range(1, CAPACITY + 1):
if weight[i - 1] <= j:
optimal[i][j] = max(optimal[i - 1][j], optimal[i - 1][j - weight[i - 1]] + value[i - 1])
else:
optimal[i][j] = optimal[i - 1][j]
print(optimal[i][j], end=" ")
print("\n", end="")
print("\nthe optimal solution is:" + str(optimal[NUM][CAPACITY]) + "\n")

def knapsack():
optimal = [0 for x in range(CAPACITY + 1)]
for i in range(0, NUM):
for j in range(CAPACITY, weight[i] - 1, -1):
optimal[j] = max(optimal[j], optimal[j - weight[i]] + value[i])
print(optimal[j], end=" ")
print("\n", end="")
print("\nthe optimal solution is:" + str(optimal[CAPACITY]) + "\n")

if __name__ == '__main__':
print("二维数组\n________")
knapsack_MATRIX()
print("一维数组\n________")
knapsack()
``````

14 声望
2 粉丝
0 条评论