参考:

http://blog.csdn.net/xiaoman111/article/details/6598213

http://www.cnblogs.com/pippo0725/articles/2046366.html

http://www.cnblogs.com/KissKnife/archive/2006/09/04/494688.html

 1 #include "stdafx.h"
2 #include <iostream>
3
4 using namespace std;
5 int length;
6 void PrintSolutions(int *flag)
7 {
8 for (int i=0; i<length; i++)
9 {
10 if (flag[i] == 1)
11 {
12 cout << i+1 << " ";
13 }
14 }
15 cout << endl;
16 }
17
18 void BagProblem(int m, int n, int *flag)
19 {
20 if(n<1 || m<1)
21 return;
22 if(m < n)
23 n = m;
24 if (n == m)
25 {
26 flag[n-1] = 1;
27 PrintSolutions(flag);
28 flag[n-1] = 0;
29 }
30 flag[n-1] = 1;
31 BagProblem(m-n, n-1, flag);
32 flag[n-1] = 0;
33
34 BagProblem(m, n-1, flag);
35 }
36
37 int main(int argc, char* argv[])
38 {
39 int m, n;
40 cout << "Please input the m and n:" << endl;
41 cin >> m >> n;
42 cout << "The solution is:" << endl;
43 length = n;
44 int *flag = (int *)malloc(sizeof(int)*n);
45 memset(flag, 0, sizeof(flag));
46 BagProblem(m,n,flag);
47 //delete flag;//这个地方犯了一个原则性的错误 new和delete成对使用, malloc应该和free成对使用,要不然就会造成内存泄露
48 free(flag);
49 return 0;
50 }

  

posted on 2011-09-15 16:31  dartagnan  阅读(819)  评论(0编辑  收藏  举报