递归实现排列类型枚举

【问题描述】
把 1~n 这 n 个整数排成一行后随机打乱顺序,输出所有可能的次序。

【输入格式】
一个整数n。

【输出格式】
按照从小到大的顺序输出所有方案,每行1个。

首先,同一行相邻两个数用一个空格隔开。

其次,对于两个不同的行,对应下标的数一一比较,字典序较小的排在前面。

【数据范围】
1 ≤ n ≤ 9

【输入样例】
3

【输出样例】
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1


题解:

#include <cstdio>
#include <cstring>
#include <iostream>
#include<algorithm>

using namespace std;

const int N = 10;

int n, a[N];
bool st[N];

void dfs(int step)
{
    // 边界
    if(step == n + 1)
    {
        for (int i = 1; i <= n ; i ++) cout << a[i] << " ";
        puts(" ");
        
        // 回溯到上一层
        return;
    }
    
    // 依次枚举每个分支,即当前位置可以填哪些数
    for (int i = 1; i <= n; i ++)
    {
        //这个数字还没选过
        if(!st[i]) 
        {
            a[step] = i;
            st[i] = true;
            
            dfs(step + 1);
            
            // 回溯
            a[step] = 0;
            st[i] = false;
        }
    }
}

int main()
{
    cin >> n;
    dfs(1);
    return 0;
}
发布了63 篇原创文章 · 获赞 5 · 访问量 828

猜你喜欢

转载自blog.csdn.net/weixin_46239370/article/details/105326309
今日推荐