Title Description
Arrangement, generally removed from the n different elements m (m≤n) elements, arranged in accordance with a certain order, called out a permutation of m elements (Arrangement) from the n elements. In particular, when m = n, this arrangement is referred to as a full permutation (Permutation).
The n = 3, m = 2, there are arranged:
1 2
1 3
2 1
2 3
3 1
3 2
Entry
Input two integers n and m (1 <= n <= 10,1 <= m <= n).
Export
All output arrangement, each arrangement per line, between the two numbers separated by a space the same arrangement.
Sample input
3 2
Sample Output
1 2
1 3
2 1
2 3
3 1
3 2
Source Code
#include <stdio.h>
#include <iostream>
bool used[10];
int ans[10];
int n,r;
void dfs(int u)
{
if(u == r + 1)//注意:是r + 1 不是r
{
for (int i = 1;i <= r;i ++)
printf("%d ",ans[i]);
printf("\n");
return ;
}
for (int i = 1;i <= n;i ++)//如果有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));
std::cin >> n;
std::cin >> r;
dfs(1);//选择第一个数字
return 0;
}