-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathb10974.java
37 lines (31 loc) · 1.04 KB
/
b10974.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
public class b10974 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean[] visited = new boolean[n + 1];
List<Integer> permutation = new ArrayList<>();
StringBuilder sb = new StringBuilder();
backtracking(n, visited, permutation, sb);
System.out.println(sb);
sc.close();
}
private static void backtracking(int n, boolean[] visited, List<Integer> permutation, StringBuilder sb) {
if (permutation.size() == n) {
for (int num : permutation) {
sb.append(num).append(" ");
}
sb.append("\n");
return;
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
visited[i] = true;
permutation.add(i);
backtracking(n, visited, permutation, sb);
permutation.remove(permutation.size() - 1);
visited[i] = false;
}
}
}
}