题目
时间限制: 1 Sec 内存限制: 64 MB
题目描述
排列与组合是常用的数学方法,桐桐刚刚学会了全排列,就想试试组合,组合就是从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
题意
输入一个n一个r,让从n个数中依次选r个数并输出全排列。
简单,直接暴力DFS。(不过我还是没搞明白大神们0ms是怎么写的。)
直接上代码。
//Time:32 ms
//Memory:1692 kb
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <math.h>
#define inf 1<<29
using namespace std;
int n,k;
int a[25];
bool pos[25];
void dfs (int step)
{
if(step==k+1)
{
for(int i=1; i<=k; ++i)
printf("%3d",a[i]);
printf("\n");
return ;
}
for(int i=a[step-1]; i<=n; ++i)
if(!pos[i])
{
pos[i]=true;
a[step] = i;
dfs(step+1);
pos[i]=false;
}
}
int main(int argc,char* argv[])
{
#ifndef ONLINE_JUDGE
freopen("1.txt","r",stdin);
#endif // ONLINE_JUDGE
ios_base::sync_with_stdio(false);
cin.tie(0);
while(cin>>n>>k)
{
memset(pos,false,sizeof(pos));
memset(a,0,sizeof(a));
a[0]=1;
dfs(1);
}
return 0;
}