“背包题目”的基本描述是:有一个背包,能盛放的物品总重量为S,设有N件物品,其重量分别为w1,w2,…,wn,希看从N件物品中选择若干物品,所选物品的重量之和恰能放进该背包,即所选物品的重量之和即是S。
递归代码:
- #include "stdafx.h"
- #include <iostream>
- #include <stdlib.h>
- using namespace std;
- const int N = 7;//物品数量
- const int S = 20;//能盛放的物品总重量
- int w[N+1] = {0, 1, 4, 3, 4, 5, 2, 7};
- int knap(int s, int n) //s为剩余重量,n为剩余可先物品数。
- {
- if(s == 0)
- {
- return 1;
- }
- if(s<0 || (s>0&&n<1))
- {
- return 0;
- }
- //第n个物品入选
- if(knap(s-w[n], n-1))
- {
- cout << w[n] << " ";
- return 1;
- }
- //第n个物品没入选
- return knap(s, n-1);
- }
- int main(int argc, char *argv[])
- {
- if(knap(S, N))
- {
- cout << endl << "OK" << endl;
- }
- else
- {
- cout << "NO" << endl;
- }
- system("PAUSE");
- return 0;
- }
非递归代码:
- // ---------------------------------------------------
- // 注1: 一般要求一个解,此程序是得到所有解
- // 注2: 由于32位unsigned int限制,最多32个物品
- // ---------------------------------------------------
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- // 物品总数
- const int N_ITEM = 5;
- // 背包能装的重量
- const int BAG = 15;
- // 初始化每个物品的重量
- int item[N_ITEM] = {2, 3, 5, 7, 8};
- // 标记数组
- int flag[N_ITEM] = {0, 0, 0, 0, 0};
- // 结果计数器
- int resultCount = 0;
- // 打印结果
- void Print();
- int main()
- {
- // 打印已知条件
- cout << "BAG Weight:" << BAG << endl;
- cout << "Item Number:" << N_ITEM << endl;
- for (int i=0; i!=N_ITEM; i++)
- {
- cout << "Item." << i+1 << " W=" << item[i] << "\t";
- }
- cout << endl;
- unsigned int count = 0;
- unsigned int all_count = 1;
- for (int i=0; i!=N_ITEM; i++)
- {
- all_count *= 2;//all_count记录可能解的个数
- }
- while (1)
- {
- // 模拟递归...列举所有flag数组可能
- // 其实就这个for循环是关键
- for (int i=0; i!=N_ITEM; i++)
- {
- if ( 0 == flag[i] )
- {
- flag[i] = 1;
- continue;
- }
- else
- {
- flag[i] = 0;
- break;
- }
- }
- // 本次重量,初始化0
- int temp = 0;
- // 按标记计算所有选中物品重量和
- for (int i=0; i!=N_ITEM; i++)
- {
- if ( 1 == flag[i] )
- {
- temp += item[i];
- }
- }
- // 满足背包重量就打印
- if ( temp == BAG )
- {
- resultCount++;
- Print();
- }
- // 如果遍历了所有情况就break掉while(1)循环
- count++;
- if (count == all_count)
- {
- break;
- }
- }
- return 0;
- }
- void Print()
- {
- cout << "Result " << resultCount << endl;
- for (int i=0; i!=N_ITEM; i++)
- {
- if ( 1 == flag[i] )
- {
- cout << "Item." << i+1 << " Weight:" << item[i] << "\t";
- }
- }
- cout << endl;
- }