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] = 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
Constraints:
1 <= n <= 15
Solutions
Solution 1: Backtracking
Thinking
Count permutations where value \(j\) at position \(i\) divides or is divided by \(i\). Full \(15!\) search is impossible, but few values fit each position.
Precompute the legal values per position, then backtrack by position while marking used numbers. Reaching \(n+1\) counts one arrangement. The divisibility lists keep the search inside the feasible set.
Assign unused numbers to each position when the divisibility condition holds.
Backtracking still expands a permutation tree and repeats the same unused-set at the same position. With \(n \le 15\) the used set fits in \(2^n\) bits.
\(f[i]\) is the number of ways to reach used-set \(i\). The pop-count is the next position; try each unused \(j\) that divides that position. \(f[0]=1\) and the full mask is the answer. Each subset is filled once.
\(f[i]\) is the number of ways to form the chosen-number mask \(i\).