A summary of the two methods of fully arranging the questions

AcWing 842. Arranging Numbers

Method 1: next_permutation(a,a+n)

#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;

int main(){
    
    
	int a[10];
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
    
    
		a[i]=i+1;
	}
	
	do{
    
    
		for(int i=0;i<n;i++){
    
    
			cout<<a[i]<<" ";
		}
		cout<<endl;
	}while(next_permutation(a,a+n));
	return 0;
	
} 

Method 2: dfs

#include<iostream>
using namespace std;

int n;
int path[10];
bool st[10];
void dfs(int t){
    
    
	if(t==n){
    
    
		for(int i=0;i<n;i++){
    
    
			cout<<path[i]<<" ";
		}
		cout<<endl;
		return;
	}
	else{
    
    
		for(int i=1;i<=n;i++){
    
    
			if(!st[i]){
    
    
				path[t]=i;
				st[i]=true;
				dfs(t+1);
				//path[t]=0;
				st[i]=false;
			}	
		}
	}
}
int main(){
    
    
	scanf("%d",&n);
	dfs(0);
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326080660&siteId=291194637