用递归算法求解简单装载问题代码
时间: 2024-11-12 19:38:54 浏览: 5
简单的递归算法
递归算法求解简单装载问题通常是指解决“0-1背包”问题,这是一个经典的动态规划问题,也可以通过分治法( Divide and Conquer)转化为递归。假设有一个背包可以承载一定重量W,有n件物品,每件物品有自己的重量w[i]和价值v[i]。目标是找到一种组合方式,使得背包内的物品总重量不超过W,同时总价值最大。
以下是使用Python编写的递归求解0-1背包问题的基本代码:
```python
def knapsack_recursive(W, wt, val, n):
# Base cases
if n == 0 or W == 0:
return 0
# If weight of the nth item is more than Knapsack capacity
# then this item cannot be included in the optimal solution
if wt[n - 1] > W:
return knapsack_recursive(W, wt, val, n - 1)
# Include the nth item, recur for remaining capacity
# and weight without the nth item
else:
include = val[n - 1] + knapsack_recursive(W - wt[n - 1], wt, val, n - 1)
# Exclude the nth item, recur for remaining capacity
exclude = knapsack_recursive(W, wt, val, n - 1)
# Return the maximum of two possibilities
return max(include, exclude)
# 示例
val = [60, 100, 120]
wt = [10, 20, 30]
W = 50
n = len(val)
print("最大价值:", knapsack_recursive(W, wt, val, n))
```
阅读全文