Blue Bridge Cup (first day)

842. Arrange numbers​​​​​​​

Given an integer n, there are many ways to arrange the numbers 1∼n in a row.

Now, please output all the permutations in dictionary order.

Input format

There is one line containing an integer n.

Output format

Output all permutations in lexicographic order, with each arrangement occupying one line.

data range:

1≤n≤7

Input example:

3

Output sample:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

 

#include<stdio.h>
#define N 8 
int n;
int std[N];
int used[N];
void dfs(int u){
	if(u>n){
		for(int i=1;i<=n;i++){
			printf("%d ",std[i]);
		}
		printf("\n"); 
	}
	for(int i=1;i<=n;i++){
		if(used[i]==0){
			std[u]=i;
			used[i]=1;
			dfs(u+1);
			std[u]=0;
			used[i]=0;
		}
	}
	
}
int main(){
	scanf("%d",&n);
	dfs(1);
	for(int i=1;i<=n;i++){
		used[i]=0;
	}
	return 0;
} 

 

92. Recursive implementation of exponential enumeration

Randomly select any number of n integers from 1∼n and output all possible choices.

Input format

Enter an integer n.

Output format

Output one solution per line.

Numbers in the same row must be arranged in ascending order, with exactly 11 spaces separating two adjacent numbers.

For solutions that do not select any number, a blank line is output.

This question has a custom validator (SPJ), and the order between the rows (different schemes) is arbitrary.

data range

1≤n≤15

Input example:

3

Output sample:


3
2
2 3
1
1 3
1 2
1 2 3
#include<stdio.h>
#define N 16
int n;
int std[N];//表示当前状态,0表示未确定,1表试未选,2表示选 
void dfs(int u){
	if(u>n){
		for(int i=1;i<=n;i++){
			if(std[i]==2){
				printf("%d ",i); 
			}
		} 
		printf("\n");
		return ;
	}
	std[u]=2;
	dfs(u+1);
	std[u]=0;
	std[u]=1;
	dfs(u+1);
	
}
int main()
{
	scanf("%d",&n);
	dfs(1);
	return 0;
 }

Guess you like

Origin blog.csdn.net/qq_71356343/article/details/128994581