描述
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
-
输入
- 第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出 - 在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例 样例输入
-
2 3 1 4 2
样例输出 -
1 2 3 12 13 14 21 23 24 31 32 34 41 42 43
DFS标程
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int n,m,used[10];
char ans[11];
void dfs(int x,int num)
{
if(num==m-1)
{
ans[m]='\0';
printf("%s\n",ans);
return;
}
int i;
for(i=1;i<=n;i++)
{
if(!used[i])
{
used[i]=1;
ans[num+1]=i+'0';
dfs(i,num+1);
used[i]=0;
}
}
}
int main()
{
int i,t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
{
memset(used,0,sizeof(used));
used[i]=1;
ans[0]=i+'0';
dfs(i,0);
}
}
return 0;
}
排列
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
int N;
cin >>N;
while(N--)
{
int n,m;
cin >> n >> m;
string str = "";
for(int i = 0 ; i < n; ++i) str+='1'+i;
set<string> res;
do
{
string tmp = str.substr(0,m);
if(res.find(tmp)==res.end())
{
cout<<tmp<<endl;
res.insert(tmp);
}
}
while(next_permutation(str.begin(),str.end()));
}
}