0-1背包问题的回溯算法实现c++
时间: 2023-10-22 08:44:18 浏览: 214
当然,下面是一个用C++实现的0-1背包问题的回溯算法:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int maxWeight = 0; // 当前最大的总重量
vector<int> bestSolution; // 当前最优的解
void backtracking(vector<int>& weights, vector<int>& values, int capacity, int currentWeight, int currentValue, int index) {
if (index == weights.size() || currentWeight == capacity) {
if (currentWeight <= capacity && currentValue > maxWeight) {
maxWeight = currentValue;
bestSolution = weights;
}
return;
}
if (currentWeight + weights[index] <= capacity) {
weights[index] = 1;
backtracking(weights, values, capacity, currentWeight + weights[index], currentValue + values[index], index + 1);
weights[index] = 0;
}
backtracking(weights, values, capacity, currentWeight, currentValue, index + 1);
}
int main() {
vector<int> weights = {2, 3, 4, 5};
vector<int> values = {3, 4, 5, 6};
int capacity = 8;
vector<int> currentSolution(weights.size(), 0);
backtracking(currentSolution, values, capacity, 0, 0, 0);
cout << "Best solution: ";
for (int i = 0; i < bestSolution.size(); i++) {
if (bestSolution[i] == 1) {
cout << weights[i] << " ";
}
}
cout << endl;
cout << "Max weight: " << maxWeight << endl;
return 0;
}
```
这是一个简单的实现,使用回溯算法来解决0-1背包问题。在回溯函数中,通过递归的方式尝试放入物品和不放入物品两种选择,然后更新当前的总重量和总价值。当遍历完所有物品或者达到背包容量时,判断当前解是否为最优解并更新最大总重量和最优解。
在示例中,我们使用了一个weights数组来表示当前物品是否被放入背包中,1表示放入,0表示不放入。最后输出最优解中物品的重量和最大总重量。
希望这个实现对你有所帮助!如果有任何问题,请随时提问。
阅读全文