列出长度为n的数组中,所有加和为m的数

时间:2023-01-05 22:02:31

参考资料:http://blog.csdn.net/zhizunwudi/article/details/12260233

例子:输入:4 6  (sum = 4, n = 6)

                    4 3 2 2 1 1

输出:

1 1 1 1 
1 1 2 
1 3 
2 2 

#include<stdio.h>
int p[1024];
int size = 0;
int partition(int *a,int low, int high)
{
int key = a[low];
int tmp = a[low];
while(low<high)
{
while(low<high&&key<=a[high]) high--;
a[low] = a[high];
while(low<high&&a[low] <= key) low++;
a[high] = a[low];
}
a[low] = tmp;
return low;
}
qsort(int *a, int from, int to)
{
if(from<to)
{
int mid = partition(a,from, to);
qsort(a,from,mid -1 );
qsort(a,mid+1,to);
}
}


void sumlist(int *a, int sum ,int from, int to)
{
int i;
//printf("sum = %d\n",sum);
if(sum < 0||to < 1) return ;
if(sum == 0)
{
for(i = 0;i< size;i++)
{
printf("%d ",p[i]);
}
printf("\n");
}else{
for(i = from;i<to;i++)
{
if(a[i] <= sum)
{
sum = sum -a[i];
p[size++] = a[i];
sumlist(a,sum,i+1,to);
sum = sum+a[i];
size--;
}
while(a[i] == a[i+1]) i++;
}
}
}


int main()
{
int sum,n;
int a[1024];
int i;
scanf("%d %d",&sum,&n);


for(i = 0;i<n;i++)
{
scanf("%d",&(a[i]));
}
printf("----------------------------------\n");
qsort(a,0,n-1);
for(i = 0;i<n;i++)
{
printf("%d ",(a[i]));
}
printf("\n");
printf("----------------------------------\n");
sumlist(a,sum,0,n);
}