C++ recursively implement permutation enumeration

Arrange the n integers from 1 to n in a row and randomly shuffle the order, and output all possible orders.
Input format
An integer n.
Output format
All schemes are output in order from smallest to largest, one per line.
First, two adjacent numbers on the same line are separated by a space.
Second, for two different rows, the numbers corresponding to the subscripts are compared one by one, and the one with the smaller lexicographic order is ranked first.
Data range
1≤n≤9
Input example:
3
Output example:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

AC code:

#include<iostream>
using namespace std;

int n;
int a[10];
bool vis[10];
int index;

void dfs(int last)//还有last位没排
{
    
    
    if(last==0)
    {
    
    
        for(int i=1;i<=n;++i)
            cout<<a[i]<<" ";
        cout<<endl;
        return;
    }
    for(int i=1;i<=n;++i)
    {
    
    
        if(!vis[i])
        {
    
    
            vis[i]=true;
            a[++index]=i;
            dfs(last-1);
            vis[i]=false;
            --index;
        }
    }
}

int main()
{
    
    
    cin>>n;
    dfs(n);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108746782