01背包问题伪代码
时间: 2023-07-07 13:12:39 浏览: 61
01背包问题的代码
以下是一个简单的01背包问题的伪代码:
```
function knapsack(weights, values, capacity):
n = length(weights)
dp = new Array(capacity+1)
for i from 0 to capacity:
dp[i] = 0
for i from 0 to n-1:
for j from capacity to weights[i] step -1:
dp[j] = max(dp[j], dp[j-weights[i]] + values[i])
return dp[capacity]
```
其中,weights是物品重量的数组,values是物品价值的数组,capacity是背包的容量。函数返回能够装入背包的最大价值。
阅读全文