Skip to content

Commit e296fe6

Browse files
committed
Add solution #526
1 parent d9c682c commit e296fe6

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,7 @@
422422
523|[Continuous Subarray Sum](./0523-continuous-subarray-sum.js)|Medium|
423423
524|[Longest Word in Dictionary through Deleting](./0524-longest-word-in-dictionary-through-deleting.js)|Medium|
424424
525|[Contiguous Array](./0525-contiguous-array.js)|Medium|
425+
526|[Beautiful Arrangement](./0526-beautiful-arrangement.js)|Medium|
425426
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
426427
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
427428
542|[01 Matrix](./0542-01-matrix.js)|Medium|
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 526. Beautiful Arrangement
3+
* https://leetcode.com/problems/beautiful-arrangement/
4+
* Difficulty: Medium
5+
*
6+
* Suppose you have n integers labeled 1 through n. A permutation of those n integers perm
7+
* (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either
8+
* of the following is true:
9+
* - perm[i] is divisible by i.
10+
* - i is divisible by perm[i].
11+
*
12+
* Given an integer n, return the number of the beautiful arrangements that you can construct.
13+
*/
14+
15+
/**
16+
* @param {number} n
17+
* @return {number}
18+
*/
19+
var countArrangement = function(n) {
20+
let count = 0;
21+
backtrack(1, 0);
22+
return count;
23+
24+
function backtrack(offset, used) {
25+
if (offset > n) {
26+
count++;
27+
return;
28+
}
29+
for (let i = 1; i <= n; i++) {
30+
if (!(used & (1 << i)) && (i % offset === 0 || offset % i === 0)) {
31+
backtrack(offset + 1, used | (1 << i));
32+
}
33+
}
34+
}
35+
};

0 commit comments

Comments
 (0)