给定一个整形数组和一个整形数,求出数组中的数相加等于给定整形数的所有组合
如int a[4]={1,2,5,10},int sum=100
组合如下:
1,1.........(100)/*100个1*/
2,2..........(50)/*50个2*/
1,1,2,2......(2,49)/*2个1,49个2*/
想到了这样的一个解法:
#include
<
stdio.h
>
void output( int os, int a[], int b[], int n)
{
int i,flag = 0 ;
printf( " " );
for (i = 0 ; i < n ; i ++ )
{
if (b[i] == 0 ) continue ;
if ( flag == 0 )
{
printf( " %2d * %2d " ,a[i] ,b[i]);
flag = 1 ;
}
else
printf( " + %2d * %2d " ,a[i],b[i]);
}
printf( " = %d " ,os);
}
void calc( int os, int s, int from, int a[], int n , int b[])
{
int i ;
if (s == 0 ) {
output(os, a,b,n);
return ;
} else {
for ( i = from ; i < n ; i ++ ) {
if (s >= a[i]) {
b[i] ++ ;
calc(os, s - a[i], i, a, n, b);
b[i] -- ;
}
}
}
}
int main()
{
int a[ 4 ] = { 1 , 2 , 5 , 10 };
int b[ 10 ] = { 0 };
int sum = 100 ;
calc(sum,sum, 0 , a, 4 ,b);
return 0 ;
}
void output( int os, int a[], int b[], int n)
{
int i,flag = 0 ;
printf( " " );
for (i = 0 ; i < n ; i ++ )
{
if (b[i] == 0 ) continue ;
if ( flag == 0 )
{
printf( " %2d * %2d " ,a[i] ,b[i]);
flag = 1 ;
}
else
printf( " + %2d * %2d " ,a[i],b[i]);
}
printf( " = %d " ,os);
}
void calc( int os, int s, int from, int a[], int n , int b[])
{
int i ;
if (s == 0 ) {
output(os, a,b,n);
return ;
} else {
for ( i = from ; i < n ; i ++ ) {
if (s >= a[i]) {
b[i] ++ ;
calc(os, s - a[i], i, a, n, b);
b[i] -- ;
}
}
}
}
int main()
{
int a[ 4 ] = { 1 , 2 , 5 , 10 };
int b[ 10 ] = { 0 };
int sum = 100 ;
calc(sum,sum, 0 , a, 4 ,b);
return 0 ;
}