做过这个题,基础题,递归解决全排列。
Problem
网上有一些比较奇怪的做法例如位运算,可以了解了解,掌握比较困难。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 10, n;
static boolean st[] = new boolean[N];
static int a[] = new int[N];
public static void main(String[] args) throws IOException {
n = Integer.parseInt(br.readLine());
dfs(1);
pw.flush();
pw.close();
br.close();
}
public static void dfs(int u) {
if (u > n) {
for (int i = 1; i <= n; i++) pw.print(a[i] + " ");
pw.println();
return;
}
for (int i = 1; i <= n; i++) {
if (!st[i]) {
st[i] = true;
a[u] = i;
dfs(u + 1);
st[i] = false;
}
}
}
}