AcWing 842. 排列数字-java
原题链接
简单
作者:
crayon不小心
,
2021-02-23 15:22:06
,
所有人可见
,
阅读 250
import java.io.*;
public class Main {
static int n;
static int N = 10;
static int [] path = new int[N]; //路径数组
static boolean [] st = new boolean[N]; //状态数组
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
//DFS
public static void main(String[] args) throws IOException {
String[] s = reader.readLine().split(" ");
n = Integer.parseInt(s[0]);
dfs(0);
writer.flush();
}
private static void dfs(int u)throws IOException
{
if(u==n)
{
for (int i = 0; i < n; i++) {
writer.write(path[i]+" ");
}
writer.write("\n");
return;
}
//如果未遍历完全 则往后开始遍历 遍历从 1 开始 终止数字 n
for (int i = 1; i <= n; i++) {
if(!st[i]) //当该点未遍历过
{
path[u] = i; //将这个点写进去
st[i] = true; //写进去的这个点 改变状态量
dfs(u + 1); //递归到下一个点 一直结束 满足 u = n 打印后return
st[i] = false; //还原现场 -->保证根节点后面的循环继续进行
}
}
}
}