- def numSquarefulPerms(n):
- if n == 0:
- return []
-
- visited = [False]*(n+1)
- graph = {x:[] for x in range(1, n+1)}
- for i in range(1, n+1):
- for j in range(1, i):
- s = i+j
- if helper(s):
- graph[i].append(j)
- graph[j].append(i)
- res = []
- for x in graph:
- dfs(graph, visited, n, res, [x], x)
- return res
- def helper(n):
- x = n
- while x*x > n:
- x = (x+n//x)//2
- return x*x == n
- def dfs(graph, visited, n, res, path, i):
- if len(path) == n:
- res.append(path[:])
- return
-
- visited[i] = True
- for j in graph[i]:
- if not visited[j]:
- dfs(graph, visited, n, res, path + [j], j)
- visited[i] = False
- for n in range(21):
- print(n, numSquarefulPerms(n))
复制代码
- (0, [])
- (1, [[1]])
- (2, [])
- (3, [])
- (4, [])
- (5, [])
- (6, [])
- (7, [])
- (8, [])
- (9, [])
- (10, [])
- (11, [])
- (12, [])
- (13, [])
- (14, [])
- (15, [[8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9], [9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8]])
- (16, [[8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9, 16], [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8]])
- (17, [[16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17], [17, 8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9, 16]])
- (18, [])
- (19, [])
- (20, [])
复制代码 [/i][/i][/i][/i] |