输入一个整数n(n <= 9),输出1、2、3、······、n这n个数的全排列(按照字典序输出)。
Input
一个整数n
Output
多行,每行表示一种排列,行内使用空格分隔相邻两数。
Sample Input
3
Sample Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
解题主要思路
深度优先搜索(dfs)
代码
import java.util.*;
public class 数字全排列1 {
private static int n = 0;
private static int[] ans;
private static boolean[] visited;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
ans = new int[n];
visited = new boolean[n];
dfs(0);
scan.close();
}
private static void dfs(int pos) {
if(pos == n) {
for(int i = 0; i < n-1; i++) System.out.print(ans[i]+" ");
System.out.println(ans[n-1]);
return;
}
for(int i = 0; i < n; i++) {
if(!visited[i]) {
ans[pos] = i+1;
visited[i] = true;
dfs(pos+1);
visited[i] = false;
}
}
}
}