算法设计与分析——回溯法——01背包问题

本文探讨了如何使用回溯法来解决经典的01背包问题,详细阐述了解题思路与步骤。贪心算法虽然能快速排序物品,但无法保证在O(n*logn)时间复杂度内找到最优解,而回溯法则能在更广泛的解决方案中寻找最佳答案。
摘要由CSDN通过智能技术生成

//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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值