题目描述
排列与组合是常用的数学方法,桐桐刚刚学会了全排列,就想试试组合,组合就是从n个元素中抽出r个元素(不分顺序且r≤n),我们可以简单地将n个元素理解为自然数1,2,......,n,从中任取r个数。
输入输出格式
输入格式
一行,两个整数n和r(1≤r≤n≤20)。
输出格式
输出所有的组合,每一个组合占一行且其中的元素按由小到大的顺序排列,所有的组合也按字典顺序。
输入输出样例
输入样例
5 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
题解
明显的dfs,因为是求组合数,待搜的数显然要大于已搜的数。
#include <iostream> #include <cstdio> using namespace std; int n, r; int a[25]; int ans; void DFS(int dep) { if(dep > r) { for(register int i = 1; i < r; ++i) { printf("%d ", a[i]); } printf("%d\n", a[r]); return; } for(register int i = a[dep - 1] + 1; i <= n; ++i) { a[dep] = i; DFS(dep + 1); } return; } int main() { scanf("%d%d", &n, &r); DFS(1); return 0; }