1.递归法
2.回朔法
void comb(int number, int count, int *pArray)
{
int i, j;
for(i = number; i >= count; --i)
{
pArray[count] = i;
if(count > 1)
{
comb(i - 1, count - 1, pArray);
printf("/n");
}
else
{
for(j = *pArray; j > 0; --j)
printf("%d ", *(pArray + j));
printf("/n");
}
}
}
int main()
{
int number = 0, count = 0, *pArray = NULL;
printf("Please input number:");
scanf("%d", &number);
printf("Please input count:");
scanf("%d", &count);
if(number < count)
{
printf("Error/n");
exit(1);
}
// 建立动态数组
pArray = malloc(sizeof(int) * (count + 1));
if(!pArray)
{
printf("memory distribute error!");
exit(1);
}
pArray[0] = count;
comb(number, count, pArray);
free(pArray);
pArray = NULL;
return 0;
}
程序运行如下:
Please input number:5
Please input count:3
5 4 3
5 4 2
5 4 1
5 3 2
5 3 1
5 2 1
4 3 2
4 3 1
4 2 1
3 2 1
2.回朔法
void comb(int number, int count)
{
int a[32], i = 0, j = 0;
a[0] = 0;
while(1)
{
while(i == count)
{
for(j = 1; j <= count; ++j)
printf("%d ", a[j]);
printf("/n");
++a[count];
if(a[count] > number)
break;
}
if(number - count + i >= a[i])
{
++i;
a[i] = a[i-1] + 1;
}
else
{
--i;
++a[i];
if(0 == i)
return;
}
}
}
int main()
{
int number = 0, count = 0, *pArray = NULL;
printf("Please input number:");
scanf("%d", &number);
printf("Please input count:");
scanf("%d", &count);
if(number < count)
{
printf("Error/n");
exit(1);
}
comb(number, count);
return 0;
}
程序运行如下:
Please input number:5
Please input count:3
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5