题目描述
找出从自然数1~n中任取r个数的所有组合。
例子:截至数3,2个数组合
自然数1~3中2个数的组合有:
1 2
1 3
2 3
注意:1 3,3 1被认为是同一种组合方案
输入格式:
输入给出截止数字和组合中数字数量(类型为整形),中间以逗号(,)隔开
输入样例:
3,2
输出样例:
自然数1~3中2个数的任意组合有:
1 2
1 3
2 3
代码:
#include<stdio.h>
#define MAX 100
int a[MAX];
void comb(int n, int r){
int i, j;
i = 0;
a[i] = 1;
do{
if(a[i] - i <= n - r + 1){
if(i == r - 1){
for(j=0;j<r;j++){
printf("%4d",a[j]);
printf("\n");
a[i]++;
continue;
}
i++;
a[i]=a[i-1]+1;
}
else{
if(i==0)
return;
a[--i]++;
}
}while(1)
}
int main(){
int x, y;
printf("请规定截止数和几个数组合(用,分隔的整数):");
scanf("%d,%d",&x,&y);
printf("自然数1~%d中%d个数的任意组合有:\n",x,y);
comb(x,y);
return 0;
}