Problem :

https://leetcode.com/problems/beautiful-arrangement/


My Solution :

class Solution:
def countArrangement(self, N):
def dfs():
if not nums:
self.ans += 1
return
i = 1 + N - len(nums)
for n in nums:
if i % n == 0 or n % i == 0:
nums.remove(n)
dfs()
nums.add(n)

self.ans = 0
nums = set(range(1, N+1))
dfs()
return self.ans


My Solution 2 :

class Solution:
def countArrangement(self, N):
def dfs(i):
if i == 0:
self.ans += 1
return
for j in range(1, N+1):
if not visited[j] and (j % i == 0 or i % j == 0):
visited[j] = 1
dfs(i-1)
visited[j] = 0

self.ans = 0
visited = [0]*(N+1)
dfs(N)
return self.ans