#526

Beautiful Arrangement

specialist · 645 · lc medium +30 · verified · 64.7% accepted · 3,398 likes · top 68%

play →

Description

Consider all permutations of the integers 1 through n. A permutation perm (1-indexed) is called beautiful when, for every index i (1 <= i <= n), at least one of these conditions holds:

- perm[i] is evenly divisible by i.

- i is evenly divisible by perm[i].

Given n, count and return the total number of beautiful arrangements.

Example 1:

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

Example 2:

Input: n = 1
Output: 1

Code

1
2
3