写一个01背包问题的代码
时间: 2023-11-30 22:04:19 浏览: 26
Sure, here's the code for the 0-1 Knapsack problem in Python:
```
def knapsack(weights, values, max_weight):
n = len(weights)
dp = [[0 for i in range(max_weight + 1)] for j in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, max_weight + 1):
if weights[i-1] <= w:
dp[i][w] = max(dp[i-1][w], values[i-1] + dp[i-1][w-weights[i-1]])
else:
dp[i][w] = dp[i-1][w]
return dp[n][max_weight]
```
To use this function, pass in a list of `weights`, a list of `values`, and the `max_weight` of the knapsack. The function returns the maximum value that can be packed into the knapsack without exceeding the `max_weight`.
I hope this helps!