Skip to main content

Beautiful Arrangement

Problem statement

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 = 2Output: 2Explanation: The first beautiful arrangement is [1,2]:    - perm[1] = 1 is divisible by i = 1    - perm[2] = 2 is divisible by i = 2The 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 = 1Output: 1

Constraints:

  • 1 <= n <= 15

My solution

/**
* @param {number} N
* @return {number}
*/
var countArrangement = function(N) {
let count = 0;
const visited = new Array(N + 1).fill(0);

function dfs(pos) {
if (pos > N) {
count++
return;
}
// console.log(visited, pos)
for (let i = 1; i < N + 1; i++) {
if (visited[i] === 0 && (pos%i === 0 || i % pos === 0)) {
visited[i] = 1;
dfs(pos + 1);
visited[i] = 0;
}
}
}

dfs(1)
return count;
};


/*
1 => 1
2 => 2
3 => 2 + 1
4 => [1, 2, 3, 4], [2, 1, 3, 4], [1, 4, 3, 2], [4, 1, 3, 2], [2, 4, 3, 1],


*/