递归版
/* Usage: Backpack Problem
Input: MaxMass--s, Maxamount--n, Mass--w1.w2....wn
Range: s--N*, n--1~15
Output: e.g.--if s=15, n=4, w1=5 w2=10 w3=5 w4=10
output: w[1]=5 w[2]=10
w[1]=5 w[4]=10
w[2]=10 w[3]=5
w[3]=5 w[4]=10
*/
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
void Search(int MAXnum);//主要作用函数
void PrintAns(int cnt);//输出一行结果
bool ChkSumMass(int cnt);//检查质量之和是否等于s
int s, n;
int AnsIndex[15];//存储物品的序号
int Mass[15];
bool chk = 0;//检查有没有输出
int main(void)
{
int i, MAXnum;
printf("Please input the total of the goods:");
scanf("%d", &n);
printf("Please input the weight of the bag:");
scanf("%d", &s);
printf("Please input the weight of each goods:");
for(i=0; i<n; i++)
scanf("%d", Mass+i);
printf("The result is:\n");
for(MAXnum=1; MAXnum<=n; MAXnum++)//按物品数递增搜索
Search(MAXnum);
if(!chk)
printf("No Solution!");
return 0;
}
void Search(int MAXnum)
{
int i, cnt;
for(i=cnt=0; ; i++)
{
if(i==n+1)
{
if(cnt!=0)
{
i = AnsIndex[--cnt];
continue;
}
else //cnt==0
break;
}
if(cnt<MAXnum)
AnsIndex[cnt++] = i;
else if(cnt == MAXnum)
{
if(ChkSumMass(cnt-1))
PrintAns(cnt);
i = AnsIndex[--cnt];
}
}
}
void PrintAns(int cnt)
{
int i;
chk = 1;
for(i=0; i<cnt; i++)
printf("w[%d] = %d ", AnsIndex[i]+1, Mass[AnsIndex[i]]);
printf("\n");
}
bool ChkSumMass(int cnt)
{
int tmp;
for(tmp=s; cnt>=0; cnt--)
tmp-=Mass[AnsIndex[cnt]];
return !tmp?1:0;
}
迭代版
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
void Search(int first, int cnt, int MAXnum);//主要作用函数
void PrintAns(int cnt);//输出一行结果
bool ChkSumMass(int cnt);//检查质量之和是否等于s
int s, n;
int AnsIndex[15];//存储物品的序号
int Mass[15];
bool chk = 0;//检查有没有输出
int main(void)
{
int i, MAXnum;
printf("Please input the total of the goods:");
scanf("%d", &n);
printf("Please input the weight of the bag:");
scanf("%d", &s);
printf("Please input the weight of each goods:");
for(i=0; i<n; i++)
scanf("%d", Mass+i);
printf("The result is:\n");
for(MAXnum=1; MAXnum<=n; MAXnum++)//按物品数递增搜索
Search(0, 0, MAXnum);
if(!chk)
printf("No Solution!");
return 0;
}
void Search(int first, int cnt, int MAXnum)
{
int index;
for(index=first; index<n; index++)//first:从上一个被存储物品的下一个开始搜索
{
AnsIndex[cnt++] = index;//假设这个物品可以放进袋子
if(cnt<MAXnum)
Search(index+1, cnt, MAXnum);//如果数量未达到设定值,放下一个物品
else if(cnt==MAXnum)
if(ChkSumMass(cnt-1))//检查是否等于s
PrintAns(cnt);
AnsIndex[--cnt]=-1;//把这个物品拿出来
}
}
void PrintAns(int cnt)
{
int i;
chk = 1;
for(i=0; i<cnt; i++)
printf("w[%d] = %d ", AnsIndex[i]+1, Mass[AnsIndex[i]]);
printf("\n");
}
bool ChkSumMass(int cnt)
{
int tmp;
for(tmp=s; cnt>=0; cnt--)
tmp-=Mass[AnsIndex[cnt]];
return !tmp?1:0;
}