Beautiful Arrangement
Suppose you have n
integers labeled 1
through n
. A permutation of those n
integers perm
(1-indexed) is considered a beautiful arrangement if for every i
(1 <= i <= n
), either of the following is true:
perm[i]
is divisible byi
.i
is divisible byperm[i]
.
Given an integer n
, return the number of the beautiful arrangements that you can construct.
Example 1:
Input: n = 2
Output: 2
Explanation:
The first beautiful arrangement is [1,2]
:
- perm[1] = 1
is divisible by i = 1
- perm[2] = 2
is divisible by i = 2
The second beautiful arrangement is [2,1]
:
- perm[1] = 2
is divisible by i = 1
- i = 2
is divisible by perm[2] = 1
Example 2:
Input: n = 1
Output: 1
Constraints:
1 <= n <= 15
Solution
Since this problem asks for the number of beautiful solutions, we will use the aggregation template for backtracking. We will fill in the logic.
- additional state:
unvisited
to store unused numbers. is_leaf
:i == n+1
, all then
numbers are used.get_edges
: all of the numbers from1
ton
is_valid
:not visited[num] and i % num == 0 or num % i == 0
, check whethernum
is unused andnum
is beautiful for indexi
.
Implementation
def countArrangement(self, n: int) -> int:
visited = [False] * (n+1)
def findBeautiful(i):
if i == n+1:
return 1
count = 0
for num in range(1, n+1):
if (not visited[num]) and (i % num == 0 or num % i == 0):
visited[num] = True
count += findBeautiful(i + 1)
visited[num] = False
return count
return findBeautiful(1)
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorHow many ways can you arrange the three letters A, B and C?
Recommended Readings
LeetCode Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way we
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!