1. 全排列
给定一个不含重复数字的数组
nums,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。输入:nums = [1,2,3] 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
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
```python
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def dfs(i, s):
if i == n:
res.append(path.copy())
return
for x in s:
path.append(x)
dfs(i+1, s - {x})
path.pop()
def dfs2(i):
if i == n:
res.append(path.copy())
return
for j in range(n):
if not on_path[j]:
path.append(nums[j])
on_path[j] = True
dfs2(i+1)
on_path[j] =False
path.pop()
path = []
n = len(nums)
on_path = [False] * n
res = []
# dfs(0, set(nums))
dfs2(0)
return res
2. N皇后
(51)按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子。 n 皇后问题 研究的是如何将
n个皇后放置在n×n的棋盘上,并且使皇后彼此之间不能相互攻击。给你一个整数n,返回所有不同的 n 皇后问题 的解决方案。每一种解法包含一个不同的 n 皇后问题 的棋子放置方案,该方案中'Q'和'.'分别代表了皇后和空位。输入:n = 4 输出:[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] 解释:如上图所示,4 皇后问题存在两个不同的解法。
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
```python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def dfs(row, cols):
if row == n:
res.append(['.'*c + 'Q' + '.'*(n-c-1) for c in path])
return
for c in cols:
if all(row+c != R+path[R] and row-c != R-path[R] for R in range(row)):
path.append(c)
dfs(row+1, cols - {c})
path.pop()
def dfs2(row):
if row == n:
res.append(['.'*c + 'Q' + '.'*(n-c-1) for c in path])
return
for c in range(n):
if not on_path[c] and not diag1[row + c] and not diag2[row - c]:
path.append(c)
on_path[c] = diag1[row + c] = diag2[ row - c ] = True
dfs2(row + 1)
on_path[c] = diag1[row + c] = diag2[row - c ] = False
path.pop()
# def valid(row, colum):
# for r in range(row):
# c = path[r]
# if row+colum == r+c or row-colum == r-c:
# return False
# return True
res = []
path = []
on_path = [False] *n
diag1 = [False] * (2*n-1)
diag2 = [False] * (2*n-1)
# dfs(0, set(range(n)))
dfs2(0)
return res