Java似乎是有亿点点慢hhh,第一次发题解ꉂ(ˊᗜˋ*)
题目描述
- 递归实现排列类型枚举 II
样例
9
1 2 3 4 5 6 7 8 9
Java 代码
import java.util.*;
import java.io.*;
public class Main {
static int N = 15;
static boolean[] vis;
static ArrayList<Integer> path = new ArrayList();
static int n;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer in = new StreamTokenizer(br);
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) {
n = (int) in.nval;
int[] a = new int[n];
for (int i = 0; i < n; ++i) {
in.nextToken();
a[i] = (int) in.nval;
}
Arrays.sort(a);
vis = new boolean[N];
dfs(0, a, out);
}
}
public static void dfs(int idx, int[] a, PrintWriter out) {
if (idx == n) {
for (int i = 0; i < n; ++i) {
out.print(path.get(i) + " ");
}
out.println();
out.flush();
return;
}
for (int i = 0; i < n; ++i) {
if (vis[i] || (i > 0 && a[i] == a[i - 1] && !vis[i - 1])) {
continue;
}
path.add(a[i]);
vis[i] = true;
dfs(idx + 1, a, out);
vis[i] = false;
path.remove(path.size() - 1);
}
}
}