Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true:
perm[i] is divisible by i.
i is divisible by perm[i].
Given an integer n, return thenumber of the beautiful arrangements that you can construct.
Input: n =2Output: 2Explanation:
The first beautiful arrangement is[1,2]:- perm[1]=1is divisible by i =1- perm[2]=2is divisible by i =2The second beautiful arrangement is[2,1]:- perm[1]=2is divisible by i =1- i =2is divisible by perm[2]=1
The problem asks for the number of permutations where, for each position, the number at that position is divisible by its index or vice versa. Since n is small (≤ 15), we can use backtracking to try all possible arrangements efficiently. Using a bitmask helps us track which numbers have been used so far.
classSolution {
int ans = 0;
publicintcountArrangement(int n) {
dfs(n, 1, 0);
return ans;
}
voiddfs(int n, int pos, int mask) {
if (pos > n) {
ans++;
return;
}
for (int num = 1; num <= n; num++) {
if ((mask & (1 << num)) == 0 && (num % pos == 0 || pos % num == 0)) {
dfs(n, pos + 1, mask | (1 << num));
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
var ans = 0funcountArrangement(n: Int): Int {
fundfs(pos: Int, mask: Int) {
if (pos > n) {
ans++return }
for (num in1..n) {
if ((mask and (1 shl num)) ==0&& (num % pos ==0|| pos % num ==0)) {
dfs(pos + 1, mask or (1 shl num))
}
}
}
dfs(1, 0)
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defcountArrangement(self, n: int) -> int:
ans: int =0defdfs(pos: int, mask: int) ->None:
nonlocal ans
if pos > n:
ans +=1returnfor num in range(1, n +1):
ifnot (mask & (1<< num)) and (num % pos ==0or pos % num ==0):
dfs(pos +1, mask | (1<< num))
dfs(1, 0)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfncount_arrangement(n: i32) -> i32 {
fndfs(n: i32, pos: i32, mask: i32, ans: &muti32) {
if pos > n {
*ans +=1;
return;
}
for num in1..=n {
if (mask & (1<< num)) ==0&& (num % pos ==0|| pos % num ==0) {
dfs(n, pos +1, mask | (1<< num), ans);
}
}
}
letmut ans =0;
dfs(n, 1, 0, &mut ans);
ans
}
}