-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
39 lines (37 loc) · 927 Bytes
/
Solution.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
38
39
class Solution {
private int n;
private int ans;
private boolean[] vis;
private Map<Integer, List<Integer>> match;
public int countArrangement(int n) {
this.n = n;
ans = 0;
vis = new boolean[n + 1];
match = new HashMap<>();
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
if (i % j == 0 || j % i == 0) {
match.computeIfAbsent(i, k -> new ArrayList<>()).add(j);
}
}
}
dfs(1);
return ans;
}
private void dfs(int i) {
if (i == n + 1) {
++ans;
return;
}
if (!match.containsKey(i)) {
return;
}
for (int j : match.get(i)) {
if (!vis[j]) {
vis[j] = true;
dfs(i + 1);
vis[j] = false;
}
}
}
}