題目鏈接:http://codeup.cn/problem.php?cid=100000608&pid=1
題目描述
排列與組合是常用的數學方法,其中組合就是從n個元素中抽出r個元素(不分順序且r < = n),我們可以簡單地將n個元素理解爲自然數1,2,…,n,從中任取r個數。
現要求你不用遞歸的方法輸出所有組合。
例如n = 5 ,r = 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
輸入
一行兩個自然數n、r ( 1 < n < 21,1 < = r < = n )。
輸出
所有的組合,每一個組合佔一行且其中的元素按由小到大的順序排列,所有的組合也按字典順序。
代碼
#include <cstdio>
int n, r;
int ans[20];
void combine(int count) {
if(count == r +1) { //遞歸出口
for(int i = 1;i <= r; i++)
printf("%d ", ans[i]);
printf("\n");
return ;
}
for(int i = ans[count - 1] + 1;i <= n; i++) { //依次枚舉
ans[count] = i;
combine(count+1);
}
}
int main() {
while(scanf("%d%d", &n, &r) != EOF) {
int count = 1;
ans[0] = 0;
combine(count);
}
return 0;
}
害 ,太菜了,不會寫非遞歸的。。。