0-1背包问题的回溯算法python
时间: 2023-04-29 17:02:17 浏览: 165
0-1背包问题 回溯算法代码
以下是-1背包问题的回溯算法Python代码:
def knapsack_backtrack(values, weights, capacity):
n = len(values)
best_value =
current_value =
current_weight =
current_items = []
best_items = []
def backtrack(i):
nonlocal best_value, current_value, current_weight, current_items, best_items
if i == n:
if current_value > best_value:
best_value = current_value
best_items = current_items.copy()
else:
if current_weight + weights[i] <= capacity:
current_items.append(i)
current_weight += weights[i]
current_value += values[i]
backtrack(i+1)
current_items.pop()
current_weight -= weights[i]
current_value -= values[i]
backtrack(i+1)
backtrack()
return best_value, best_items
# 示例
values = [10, 20, 30]
weights = [5, 10, 15]
capacity = 25
print(knapsack_backtrack(values, weights, capacity)) # 输出 (50, [, 2])
阅读全文