A permutation of the integers 1, 2, ..., n
is considered a beautiful arrangement if for every integer i
, the following condition is met:
i
is divisible by the position it is placed in (i.e., the element at index i
is divisible by i
), or the position is divisible by the element i
(i.e., i
is divisible by the element at index i
).Given an integer n
, the task is to find how many beautiful arrangements can be constructed.
n
?
n
will be a small integer, as large values may result in combinatorially large numbers of permutations. The constraints can be found in the problem statement on LeetCode.This problem can be effectively solved using backtracking. We will generate permutations of the integers from 1
to n
and for each permutation, we will check if it satisfies the beautiful arrangement condition.
Here is a step-by-step approach:
def countArrangement(n: int) -> int:
def backtrack(pos):
# Base case: if pos exceeds n, then we've placed all numbers correctly.
if pos > n:
return 1
count = 0
for num in range(1, n+1):
if not used[num] and (num % pos == 0 or pos % num == 0):
used[num] = True
count += backtrack(pos + 1)
used[num] = False
return count
# Initialize the used numbers array
used = [False] * (n + 1)
# Kick off the backtracking from position 1
return backtrack(1)
# Example usage:
n = 3
print(countArrangement(n)) # Output: 3
The time complexity of this solution is O(k), where k
depends on the potential number of permutations we process. In the worst case, we might generate all n! permutations. However, due to our constraints and checks, not all permutations are fully generated and many branches are pruned early.
used
array and recursion call stack.By implementing and employing backtracking, we efficiently search through possible permutations while pruning invalid configurations early, resulting in an effective solution for relatively small values of n
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?