用回溯法求解01背包问题
#include <iostream>
#include<vector>
using namespace std;
#define N 4
int n = N ; //物品个数
vector<int> w; //重量
vector<int> v; //价值
int c = 13; //背包容量
int value = 0; //当前价值
int weight = 0; //当前重量
vector<int> path; // 当前解空间
vector< vector<int> > result ; //存放所有解
int OptimaValue = 0; //最优价值
vector<int> OptimaSolution(N);// 最优解
void backtracking(int Anext){
if(path.size() == N){
if(value > OptimaValue){ //如果当前价值大于最优价值
OptimaSolution=path;
OptimaValue = value;
}
result.push_back(path);
path.clear();
return;
}
for(int i = 0;i <= 1; i++){ //两个分支,当前第Anext个物品是否放入
if(i == 1 && w[Anext] + weight <= c){ //重量小于背包容量,选择放入
path.push_back(1);
value += v[Anext];
weight += w[Anext];
backtracking( Anext+1);
path.pop_back();
path.push_back(0);
value -= v[Anext];
weight -= w[Anext];
}
else{ //不放入
path.push_back(0);
backtracking(Anext+1);
path.pop_back();
}
}
}
void out(){
backtracking(0); //从第0个物品开始
for(const auto &a: result){ //遍历所有解
for(const auto &b:a){
cout<< b <<" ";
}
cout<< "\"" <<endl;
}
return;
}
int main() {
std::cout << "Hello, World!" << std::endl;
v.push_back(12);
v.push_back(11);
v.push_back(9);
v.push_back(8);
w.push_back(8);
w.push_back(6);
w.push_back(4);
w.push_back(3);
out();
return 0;
}
用clion运行的时候,Anext=0,递归调用backtracking(Anext+1)时候,Anext直接变为1000多
报 信号=SIGSEGV(Segmentation fault)
望解答