Chapter 1 Recursively implement permutation enumeration

Full arrangement

All ranks can be scored as violent in many questions in the early stage

Title description

Arrange the n(n<10) integers from 1 to n in a row and randomly shuffle the order, and output all possible orders.

Input and output

Input

An integer n.

Output

Output all schemes in order from smallest to largest, 1 per line. First, two adjacent numbers on the same line are separated by a space. Secondly, 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.

#include <bits/stdc++.h>
using namespace std;
int n,a[20];
bool flag[20];
void dfs(int x)
{
    
    
	if(x==n+1)
	{
    
    
		printf("%d",a[1]);
		for(int i=2;i<=n;i++)
		    printf(" %d",a[i]);
		cout<<'\n';
		return;
	}
	for(int i=1;i<=n;i++)
	{
    
    
		if(!flag[i])
		{
    
    
			flag[i]=1;
			a[x]=i;
			dfs(x+1);
			flag[i]=0;
		}
	}
}
int main()
{
    
    
	cin>>n;
	dfs(1);
	return 0;
}

Guess you like

Origin blog.csdn.net/ydsrwex/article/details/112253196