11"""
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),
2+ Suppose you have n integers labeled 1 through n.
3+ A permutation of those n integers
4+ perm (1-indexed) is considered a
5+ "beautiful arrangement" if for every i (1 <= i <= n),
46either of the following is true:
57
68-> perm[i] is divisible by i.
79-> i is divisible by perm[i].
8- Given an integer n, return the number of the "beautiful arrangements" that you can construct.
10+ Given an integer n, return the number of the
11+ "beautiful arrangements" that you can construct.
912
1013"""
1114# Solution using Backtracking
@@ -15,8 +18,10 @@ class BeautifulArrange:
1518 def countarrangement (self , n : int ) -> int :
1619 self .count = 0
1720 """
18- We initialize a counter to record how many valid arrangements we find.
19- Using self.count lets the nested function modify it without nonlocal.
21+ We initialize a counter to record how
22+ many valid arrangements we find.
23+ Using self.count lets the nested
24+ function modify it without nonlocal.
2025 """
2126
2227 used = [False ] * (n + 1 )
@@ -28,7 +33,8 @@ def countarrangement(self, n: int) -> int:
2833 def backtrack (pos ):
2934 """
3035 Define the recursive backtracking function.
31- pos is the current position in the permutation we are filling (1-indexed).
36+ pos is the current position in the
37+ permutation we are filling (1-indexed).
3238 We try to assign a number to position pos.
3339 """
3440 if pos > n :
@@ -40,9 +46,11 @@ def backtrack(pos):
4046 ): # Try every candidate number num for the current position pos.
4147 """
4248 Two checks in one:
43- 1. not used[num] — the number num has not been placed yet (we can use it).
44- 2. (num % pos == 0 or pos % num == 0) — the beautiful-arrangement condition:
45- number num is compatible with position pos (either num divides pos or pos divides num).
49+ 1. not used[num] — the number num has
50+ not been placed yet (we can use it).
51+ 2. (num % pos == 0 or pos % num == 0) —
52+ the beautiful-arrangement condition:
53+ either num divides pos or pos divides num.
4654 If both are true, num is a valid choice for pos.
4755
4856 """
0 commit comments