Skip to content

Commit 4fcf7ff

Browse files
committed
Create beautiful-arrangement
1 parent e2a78d4 commit 4fcf7ff

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Suppose you have n integers labeled 1 through n. A permutation of those n integers
3+
perm (1-indexed) is considered a "beautiful arrangement" if for every i (1 <= i <= n),
4+
either of the following is true:
5+
6+
-> perm[i] is divisible by i.
7+
-> i is divisible by perm[i].
8+
Given an integer n, return the number of the "beautiful arrangements" that you can construct.
9+
10+
"""
11+
# Solution using Backtracking
12+
13+
class Solution:
14+
# funtion call; n is the size of the permutation (numbers 1..n)
15+
def countArrangement(self, n: int) -> int:
16+
17+
self.count = 0
18+
"""
19+
We initialize a counter to record how many valid arrangements we find.
20+
Using self.count lets the nested function modify it without nonlocal."""
21+
22+
used = [False] * (n + 1)
23+
"""
24+
A boolean list to mark which numbers have already been placed in the permutation.
25+
"""
26+
27+
def backtrack(pos):
28+
"""
29+
Define the recursive backtracking function.
30+
pos is the current position in the permutation we are filling (1-indexed).
31+
We try to assign a number to position pos.
32+
"""
33+
if pos > n:
34+
35+
self.count += 1 # We found a complete valid arrangement, so increment the total count.
36+
return
37+
for num in range(1, n + 1): # Try every candidate number num for the current position pos.
38+
39+
40+
"""
41+
Two checks in one:
42+
1. not used[num] — the number num has not been placed yet (we can use it).
43+
2. (num % pos == 0 or pos % num == 0) — the beautiful-arrangement condition:
44+
number num is compatible with position pos (either num divides pos or pos divides num).
45+
If both are true, num is a valid choice for pos.
46+
47+
"""
48+
if not used[num] and (num % pos == 0 or pos % num == 0):
49+
used[num] = True
50+
backtrack(pos + 1)
51+
used[num] = False
52+
53+
backtrack(1)
54+
return self.count

0 commit comments

Comments
 (0)