Beautiful Arrangement — LeetCode 526 Python Solution
- Problem
- #526
- Pattern
- Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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 by i.
Example
- Input
- n = 2
- Output
- 2
- Explanation
- The first beautiful arrangement is [1,2]:
Python solution
class Solution:
def countArrangement(self, n: int) -> int:
def dfs(i):
nonlocal ans, n
if i == n + 1:
ans += 1
return
for j in match[i]:
if not vis[j]:
vis[j] = True
dfs(i + 1)
vis[j] = False
ans = 0
vis = [False] * (n + 1)
match = defaultdict(list)
for i in range(1, n + 1):
for j in range(1, n + 1):
if j % i == 0 or i % j == 0:
match[i].append(j)
dfs(1)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 526. Beautiful Arrangement is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 526. Beautiful Arrangement?
- LeetCode 526. Beautiful Arrangement is rated Medium on LeetCode.
- What topics does LeetCode 526. Beautiful Arrangement cover?
- LeetCode 526. Beautiful Arrangement is tagged Bit Manipulation, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.