## Algorithm

Problem Name: 526. Beautiful Arrangement

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 the number of the beautiful arrangements that you can construct.

Example 1:

```Input: n = 2
Output: 2
Explanation:
The first beautiful arrangement is [1,2]:
- perm = 1 is divisible by i = 1
- perm = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
- perm = 2 is divisible by i = 1
- i = 2 is divisible by perm = 1
```

Example 2:

```Input: n = 1
Output: 1
```

Constraints:

• `1 <= n <= 15`

## Code Examples

### #1 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
var countArrangement = function(N) {
let used = Array(N + 1).fill(false)
let res = 0
function backtrack(curIdx) {
if (curIdx === 0) return res++
for (let i = 1; i <= N; i++) {
if (used[i]) continue
if (i % curIdx === 0 || curIdx % i === 0) {
used[i] = true
backtrack(curIdx - 1)
used[i] = false
}
}
}
backtrack(N)
return res
};
``````
Copy The Code &

Input

cmd
n = 2

Output

cmd
2

### #2 Code Example with Python Programming

```Code - Python Programming```

``````
memo = {}
class Solution:
def countArrangement(self, N, arr = None):
if not arr: arr = tuple(range(1, N + 1))
if (N, arr) in memo or N == 1: return N == 1 and 1 or memo[(N, arr)]
memo[(N, arr)] = sum([self.countArrangement(N-1, arr[:j]+arr[j + 1:]) for j in range(len(arr)) if arr[j]%N==0 or N%arr[j]==0])
return memo[(N, arr)]
``````
Copy The Code &

Input

cmd
n = 2

Output

cmd
2