823. 排列
给定一个整数 nn,将数字 1∼n1∼n 排成一排,将会有很多种排列方法。
现在,请你按照字典序将所有的排列方法输出。
输入格式
共一行,包含一个整数 nn。
输出格式
按字典序输出所有排列方案,每个方案占一行。
数据范围
1≤n≤91≤n≤9
输入样例:
3
输出样例:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
题解
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.*;
public class Main {
public static int n;
public static int a[] = new int[10];
public static int book[] = new int[10];
public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args)throws Exception {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
dfs(1);
bw.flush();
}
public static void dfs(int step) throws Exception{
if (step == n + 1) {
for (int i = 1 ; i <= n ; i ++){
//System.out.print(a[i]+" ");
bw.write(a[i]+" ");
}
//System.out.println();
bw.write("\n");
return;
}
for(int i = 1 ; i <= n ; i ++){
if (book[i] == 0) {
a[step] = i;
book[i] = 1;
dfs(step+1);
book[i] = 0;
}
}return;
}
}
评论区