-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbeautiful_arrangement.py
48 lines (37 loc) · 1.2 KB
/
beautiful_arrangement.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
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.
i is divisible by perm[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
"""
class Solution:
def countArrangement(self, n: int) -> int:
def dfs(index, sol):
nonlocal res
if len(sol) == n:
res = res + 1
return
for num in range(1, n + 1):
if num not in sol and (num % index == 0 or index % num == 0):
sol.append(num)
dfs(index + 1, sol)
sol.pop()
res = 0
sol = []
dfs(1, [])
return res