0-1背包。有 N 件物品,背包能承受的最大重量是 M。总重量不超过背包可承受的最大重量,且价值总和最大。针对这个问题,写出几种由python实现的代码
时间: 2024-12-08 13:15:26 浏览: 10
0-1背包问题是一个经典的动态规划问题,在Python中可以使用递归或迭代的方式来解决。以下是两种常见的实现方法:
**1. 递归解法(Brute Force):**
```python
def knapsack_recursion(weights, values, capacity, n):
if n == 0 or capacity == 0:
return 0
elif weights[n - 1] > capacity:
return knapsack_recursion(weights, values, capacity, n - 1)
else:
include = values[n - 1] + knapsack_recursion(weights, values, capacity - weights[n - 1], n - 1)
exclude = knapsack_recursion(weights, values, capacity, n - 1)
return max(include, exclude)
# 使用示例
weights = [2, 3, 4, 5]
values = [6, 9, 7, 10]
capacity = 8
n = len(weights)
max_value = knapsack_recursion(weights, values, capacity, n)
```
**2. 动态规划(Dynamic Programming):**
```python
def knapsack_dp(weights, values, capacity, n):
dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 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][capacity]
# 使用示例同上
max_value = knapsack_dp(weights, values, capacity, n)
```
在这两个函数中,`weights`存储物品重量,`values`存储物品价值,`capacity`是背包容量,`n`是物品数。`knapsack_recursion`会遍历所有可能的组合,而`knapsack_dp`则利用了状态转移方程来避免重复计算。
阅读全文