JS
$\color{#9933ff}{Web应用-题解}$
let buf = '';
process.stdin.on('readable', function() {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let path = [];
let st = [];
let dfs = (u, n) => {
if (u === n) console.log(path.join(' '));
else {
for (let i = 1; i <= n; i ++) {
if (!st[i]) {
path.push(i);
st[i] = true;
dfs (u + 1, n);
st[i] = undefined;
path.pop(); // 将最后一个数删掉
}
}
}
}
process.stdin.on('end', function() {
let n = parseInt(buf);
dfs(0, n);
});
Java
$dfs从0开始$
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class Main {
private static int[] path;
private static boolean[] st;
private static int n;
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static void dfs(int u) throws Exception {
if (u == n) {
for (int i = 0; i < n; i ++ )
bw.write(path[i] + 1 + " ");
bw.write("\n");
} else {
for (int i = 0; i < n; i ++ )
if (!st[i]) {
path[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
}
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
path = new int[n];
st = new boolean[n];
dfs(0);
bw.flush();
}
}
$dfs从1开始$
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
public class Main {
private static int[] path;
private static boolean[] st;
private static int n;
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static void dfs(int u) throws Exception {
if (u > n) {
for (int i = 1; i <= n; i ++ )
bw.write(path[i] + " ");
bw.write("\n");
} else {
for (int i = 1; i <= n; i ++ )
if (!st[i]) {
path[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false; // 恢复现场
}
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
path = new int[n + 1];
st = new boolean[n + 1];
dfs(1);
bw.flush();
}
}