0-1背包问题

01背包问题;考虑简化了的背包问题:

设有一个背包可以放入的物品重量为s,现有n件物品,重量分别为 w0,w1,...,wn-1,问能否从这n件物品中选择若干件放入背包,使其重量和证号为s。

如果存在一种符合上述要求的选择,则称此问题有解,否则无解。

使用递归方法,则此问题轻而易举的就解决了:

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int *w;
 5 bool knap(int s, int n)
 6 {
 7     if (s == 0)
 8     {
 9         return true ;
10     }
11     if((s < 0) || (s>0 && n<1))
12     {
13         return false;
14     }
15     if(knap(s-w[n-1], n-1))
16     {
17         cout<< w[n-1] <<" " ;
18         return true;
19     }
20     else 
21     {
22         return knap(s, n-1);
23     }
24 }
25 
26 int main( )
27 {
28     int num;
29     int sw;
30     cout<< "input sw and num : " << endl;
31     cin>> sw >> num;
32     w=new int[num];
33     cout<<"input the w in turn : " << endl;
34     for (int i=0;i<num;i++)
35     {
36         cin>> w[i];
37     }
38     cout<< "The result : " << endl;
39     knap(sw, num);
40     cout<< endl;
41     return 0;
42 }

详细解答可以参考这篇博文:http://www.cnblogs.com/jiangjun/archive/2012/05/08/2489590.html

posted @ 2013-05-22 10:42  Air Support  阅读(205)  评论(0编辑  收藏  举报