简单背包问题,时间复杂度为指数级
背包问题:有一个背包,能装入的物品总重量为S,设有N件物品,其重量分别为W1,W2,……,WN。希望从N件物品中选择若干件物品,所选物品的重量之和恰能放入该背包,即所选物品的重量之和等于S。试编程求解。
#include <iostream>
using namespace std;
int path[10];
int i=-1;
bool simple_bag(int capacity,int weight[],int n)
{
if (capacity == 0) { path[++i] = n; return true; }
if (capacity < 0 || capacity>0 && n < 1) return false;
if (simple_bag(capacity - weight[n - 1], weight, n - 1)) { path[++i] = n; return true; }
else return simple_bag(capacity,weight,n-1);
}
int main()
{
int weight[10] = { 1,100,3,56,5 ,2,3,4,5,1};
cout << simple_bag(168, weight, 10)<<endl;
while(i)
cout << path[i--]<<'#';
}