这是一个子集和问题,经过了一定修改,即输入一个数n,则自动生成含有n个随机不重复元素的数组。
然后输入自己想要求的和sum,则会输出所有的结果(没有正确的结果则什么都不输出)
(在运行程序时,可以尝试输入50和200)(50为数组元素个数,200为sum)
基本上程序会一直运行,因为结果的可能性太多了,所以希望能将重复的结果去掉,只输出重复中的一个。
比如:
像图片这样,结果元素是一样的,只是顺序不同,
怎么将重复的去掉,相同元素的情况下,只保存一个(类似图片中的只输出其中一个)
(因为当元素个数过多时,结果的可能性太多了,导致程序运行不完)
另外同一个元素可能会被调用两次甚至三次(比如0,不管几个0不会影响sum,所以0可能会被调用n次),怎样使元素只被调用一次。
请大神们帮忙改写一下程序发给我,要交作业了,水平不行,真的改不出来。
另外帮忙修改一下,将随机生成的数组输出出来,这样方便确认。(在这谢谢你们了)
代码如下:
#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 n:");
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;
}
更多 0