File tree 2 files changed +36
-0
lines changed
2 files changed +36
-0
lines changed Original file line number Diff line number Diff line change 422
422
523|[ Continuous Subarray Sum] ( ./0523-continuous-subarray-sum.js ) |Medium|
423
423
524|[ Longest Word in Dictionary through Deleting] ( ./0524-longest-word-in-dictionary-through-deleting.js ) |Medium|
424
424
525|[ Contiguous Array] ( ./0525-contiguous-array.js ) |Medium|
425
+ 526|[ Beautiful Arrangement] ( ./0526-beautiful-arrangement.js ) |Medium|
425
426
530|[ Minimum Absolute Difference in BST] ( ./0530-minimum-absolute-difference-in-bst.js ) |Easy|
426
427
541|[ Reverse String II] ( ./0541-reverse-string-ii.js ) |Easy|
427
428
542|[ 01 Matrix] ( ./0542-01-matrix.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments