本文共 578 字,大约阅读时间需要 1 分钟。
#include "stdafx.h"#includeusing namespace std;int length;void PrintSolutions(int *flag) { for (int i=0; i > m >> n; cout << "The solution is:" << endl; length = n; int *flag = (int *)malloc(sizeof(int)*n); memset(flag, 0, sizeof(flag)); BagProblem(m,n,flag); //delete flag;//这个地方犯了一个原则性的错误 new和delete成对使用, malloc应该和free成对使用,要不然就会造成内存泄露 free(flag); return 0; }
上面的代码看懂不是很难吧,递归的程序就是可读性好,我觉得这个代码的亮点应该就是flag数组的使用,充分利用了递归的性质,只是很简单的一个数组就完成了所有组合的输出。在每次把flag[i]设置为1之后就进入递归,代表了将i放入背包,当退出递归函数的时候,肯定要将flag[i]赋为0,因为这时候i已经不在背包中了。
转载地址:http://hbsvi.baihongyu.com/