Title Description
R out problem is a combination of elements from n elements in (and regardless of order r <= n),
We can simply be understood n elements is a natural number 1,2, ..., n, which take any number r.
E.g. n = 5, r = 3, all combination:
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
Entry
Two row natural number n, r (1 <n <21,1 <= r <= n).
Export
All combinations, each combination per line and wherein elements are arranged in ascending order, all combinations are lexicographic order.
Sample input
5 3
Sample Output
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
Source Code
#include <stdio.h>
#include <iostream>
using namespace std;
bool used[30];
int ans[30];
int n,r;
void dfs(int u)
{
if(u == r + 1)//注意:是r + 1 不是r //如果满足R个数据,则输出
{
for (int i = 1;i <= r;i ++)
printf("%d ",ans[i]);
printf("\n");
return ;
}
for (int i = ans[u - 1] + 1;i <= n;i ++)//注意:i的起点是ans[u - 1] + 1 如果有n个数字,就循环n次来检查是否被选中
{
if(used[i] == 0)//如果没有被选中
{
ans[u] = i;//如果没有被选中,就把i放到ans[]中
used[i] = 1;//used[2] = 1表示2这个数已经被选过了 used[3] = 1表示3这个数已经被选过了
dfs(u + 1);//继续选下一个数字 dfs(1):选第1个数 dfs(2):选第2个数 dfs(n + 1):打印,退出
used[i] = 0;//打印完毕,把该数字取消
}
}
}
int main()
{
memset(used,0,sizeof(used));
cin >> n;
cin >> r;
dfs(1);//选择第一个数字
return 0;
}