Exemplo n.º 1
0
void subsetsum(int b[],int a[],int i,int sum,int j)
{
     int s=0,c[N],k=0;
    if(i<N-1)
    {
            if(sum==summ)
            {

                    for(k=0;k<j;k++)
                    {
                         if(b[k]==0)
                            continue;
                         printf("%d  ",b[k]);
                    }
                    printf("\n");
                    k=0;
            }


          else
           {
                   subsetsum(b,a,i+1,sum,j);
                   for(k=0;k<j;k++)
                        c[k]=b[k];
                   c[k]=a[i+1];

                   if(sum<summ)
                    {
                         s=sum+a[i+1];
                         subsetsum(c,a,i+1,s,j+1);
                    }
          }
    }
}
Exemplo n.º 2
0
int main()
{
    int a[N]={1,3,2,4,5,1,7},b[N],i=0;
    printf("enter the value of summ\n");
    scanf("%d",&summ);
    b[0]=0;
    subsetsum(b,a,-1,0,1);
    getch();
}
Exemplo n.º 3
0
int main()
{
	frequency_t a[] = { {6, 4}, {9, 3}, {3, 1} };
	int N = sizeof(a)/sizeof(*a);
	int sum = 27;
	int* result = (int*) malloc(sizeof(int) * sum);

	subsetsum(a, N, sum, result, 0);

	return 0;
}
Exemplo n.º 4
0
/*
a	: pointer to an array of frequency_t elements.
N	: size of the above array.
sum	: sum we are looking for.
result	: array where selected numbers will be stored.
index	: caller must initially setup result and index.
*/
void subsetsum(frequency_t* a, int N, int sum, int* result, int index)
{
	if(N == 0) return;

	int psum = sum - a[0].item;

	//we cannot use an element if its frequency count is <= zero.
	if(a[0].count <= 0) goto try_with_next_element;

	result[index] = a[0].item;
	//if psum is zero, we found a combination which adds up to sum, so print it. otherwise decrease the frequency
	//count of the current element and make a recursive call.
	if(psum == 0)
		printsubset(result, index + 1);
	else
	{
		--a[0].count;
		subsetsum(a, N, psum, result, index + 1);
		++a[0].count;
	}
	
try_with_next_element:
	subsetsum(a + 1, N - 1, sum, result, index);
}
int main()
{
    int a[]={1,2,3};
    printf("%lld",subsetsum(a,sizeof(a)/sizeof(*a)));
    getchar();
}