排列的输出

问题 F: 排列的输出

时间限制: 1 Sec  内存限制: 128 MB
提交: 100  解决: 74
[提交][状态][讨论版][命题人:quanxing]

题目描述

排列与组合是常用的数学方法,其中排列就是从n个元素中抽出r个元素(分顺序且r≤n),我们可以简单地将n个元素理解为自然数1,2,…,n,从中任取r个数。

现要求你用递归的方法输出所有排列。

例如n=4,r=3,所有排列及排列数为:
1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
number=24

输入

n、r(1<n<21,1≤r≤n)。

输出

 

样例输入

4 3

样例输出

1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
number=24

解题思路:直接开一个for循环递归跑一遍,符合条件就输出即可。
#include <iostream>

using namespace std;

int n,m,cnt=0;
int num[21];
bool mark[21];

void cout2()
{
    for(int i=1;i<=m-1;i++)cout<<num[i]<<" ";
    cout<<num[m]<<endl;
}

void dfs(int x)
{
    for(int i=1;i<=n;++i)
    {
        if(!mark[i])
        {
            num[x]=i;
            mark[i]=true;
            if(x==m){cout2();cnt++;}
            else dfs(x+1);
            mark[i]=false;
        }
    }
}

int main()
{
    cin>>n>>m;
    dfs(1);
    cout<<"number="<<cnt<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wjw2018/p/9292732.html