//0-1背包问题 回溯法求解
#include<bits/stdc++.h>
#include <iostream>
using namespace std;
template<class Typew,class Typep>
class Knap
{
public:
Typep Bound(int i);
void Backtrack(int i);
Typew c; //背包容量
int n; //物品数
Typew *w; //物品重量数组
Typep *p; //物品价值数组
Typew cw; //当前重量
Typep cp; //当前价值
Typep bestp;//当前最后价值
};
template<class Typew,class Typep>
Typep Knapsack(Typep p[],Typew w[],Typew c,int n);
template <class Type>
inline void Swap(Type &a,Type &b);
template<class Type>
void BubbleSort(Type a[],int n);
int main()
{
int n;
int c = 7;//背包容量
cout<<"请输入物品数目:"; //物品数
cin>>n;
int p[n+1];// p[] = {0,9,10,7,4};//物品价值 下标从1开始
p[0]=0;
int w[n+1];//int w[] = {0,3,5,2,1};//物品重量 下标从1开始
w[0]
算法设计与分析——回溯法——01背包问题
本文探讨了如何使用回溯法来解决经典的01背包问题,详细阐述了解题思路与步骤。贪心算法虽然能快速排序物品,但无法保证在O(n*logn)时间复杂度内找到最优解,而回溯法则能在更广泛的解决方案中寻找最佳答案。
摘要由CSDN通过智能技术生成