69,336
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 1000
//global variables
int n=0;//the number of numbers
int c=0;//the sum of the subset
int num[MAX]={0};
int count=1;//the number of the element in a subset
int result[MAX]={0}; //the answer of this question
int c_sum=0;//current sum
//prototypes
void swap(int &a,int &b);
void back_subset(int i);
void get_random(int *a, int len);
int main()
{
//declaration
//int i=0;
printf("Please input the number of the numbers:");
scanf("%d",&n);
printf("Please input the sum:");
scanf("%d",&c);
get_random(num, n);
/*
for(i=1;i<=n;i++)
scanf("%d",&num[i]);
*/
back_subset(1);
//getch();
}
void get_random(int *a, int len)
{
int i;
srand((unsigned)time(NULL));
for(i=0;i<len;i++)
a[i] = rand() % 100;
}
void back_subset(int i)
{
if(c_sum+num[i]==c)
{
result[count]=num[i];
for(int temp=1;temp<=count;temp++)
printf("%d ",result[temp]);
printf("\n\n\n\n----------separate line------------------\n\n\n\n");
return ;
}
if(i>n)
return ;
if(c_sum+num[i]>c)
return;
for(int j=i;j<=n;j++)
{
result[count++]=num[j];
c_sum+=num[j];
swap(num[i],num[j]);
back_subset(i+1);
swap(num[i],num[j]);
c_sum-=num[j];
count--;
}
}
void swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
参考一下吧