Skip to content

Commit 69a579b

Browse files
committed
Update beautiful_arrangement.py
2 parents fb5ecf4 + 3a5a18c commit 69a579b

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

dynamic_programming/beautiful_arrangement.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
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. A permutation of those n integers
3+
perm (1-indexed) is considered a "beautiful arrangement" if for every i (1 <= i <= n),
44
either of the following is true:
55
66
-> perm[i] is divisible by i.
@@ -25,35 +25,32 @@ def countarrangement(self, n: int) -> int:
2525
A boolean list to mark which numbers have
2626
already been placed in the permutation.
2727
"""
28-
28+
2929
def backtrack(pos):
3030
"""
3131
Define the recursive backtracking function.
32-
pos is the current position in the permutation we are filling (1-indexed).
32+
pos is the current position in the permutation we are filling (1-indexed).
3333
We try to assign a number to position pos.
3434
"""
3535
if pos > n:
36-
37-
self.count += 1
36+
self.count += 1
3837
# We found a complete valid arrangement, so increment the total count.
3938
return
40-
for num in range(1, n + 1):
41-
# Try every candidate number num for the current position pos.
42-
43-
39+
for num in range(
40+
1, n + 1
41+
): # Try every candidate number num for the current position pos.
4442
"""
4543
Two checks in one:
4644
1. not used[num] — the number num has not been placed yet (we can use it).
47-
2. (num % pos == 0 or pos % num == 0) — the
48-
beautiful-arrangement condition:
49-
either num divides pos or pos divides num.
45+
2. (num % pos == 0 or pos % num == 0) — the beautiful-arrangement condition:
46+
number num is compatible with position pos (either num divides pos or pos divides num).
5047
If both are true, num is a valid choice for pos.
51-
48+
5249
"""
5350
if not used[num] and (num % pos == 0 or pos % num == 0):
5451
used[num] = True
5552
backtrack(pos + 1)
5653
used[num] = False
57-
54+
5855
backtrack(1)
5956
return self.count

0 commit comments

Comments
 (0)