Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions problems/0052.N皇后II.md
Original file line number Diff line number Diff line change
Expand Up @@ -305,3 +305,47 @@ class Solution {
}
```

### Python

```python
class Solution:
def totalNQueens(self, n: int) -> int:
count = 0
chessboard = [['.'] * n for _ in range(n)] # 初始化棋盘

def is_valid(row: int, col: int) -> bool:
# 检查列是否有皇后
for i in range(row):
if chessboard[i][col] == 'Q':
return False
# 检查45度角(左上)是否有皇后
i, j = row - 1, col - 1
while i >= 0 and j >= 0:
if chessboard[i][j] == 'Q':
return False
i -= 1
j -= 1
# 检查135度角(右上)是否有皇后
i, j = row - 1, col + 1
while i >= 0 and j < n:
if chessboard[i][j] == 'Q':
return False
i -= 1
j += 1
return True

def backtracking(row: int) -> None:
nonlocal count
if row == n:
count += 1
return
for col in range(n):
if is_valid(row, col):
chessboard[row][col] = 'Q' # 放置皇后
backtracking(row + 1)
chessboard[row][col] = '.' # 回溯

backtracking(0)
return count
```

29 changes: 29 additions & 0 deletions problems/0207.课程表.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,32 @@ public:
}
};
```

## 其他语言版本

### Python

```python
from collections import deque
from typing import List

class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
in_degree = [0] * numCourses # 每门课程的入度
graph = [[] for _ in range(numCourses)] # 邻接表:pre -> [后续课程]
for cur, pre in prerequisites:
# 上 cur 之前必须先上 pre,即 pre -> cur
graph[pre].append(cur)
in_degree[cur] += 1

que = deque([i for i in range(numCourses) if in_degree[i] == 0]) # 入度为0的课程入队
count = 0
while que:
cur = que.popleft()
count += 1 # 已修课程数 +1
for nxt in graph[cur]:
in_degree[nxt] -= 1 # 后续课程入度 -1
if in_degree[nxt] == 0:
que.append(nxt)
return count == numCourses
```
19 changes: 19 additions & 0 deletions problems/1791.找出星型图的中心节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,23 @@ public:
};
```

## 其他语言版本

### Python

```python
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
# 统计各个节点的度,只有中心节点的度会大于1
degree = {}
for u, v in edges:
degree[u] = degree.get(u, 0) + 1
degree[v] = degree.get(v, 0) + 1
if degree[u] > 1:
return u
if degree[v] > 1:
return v
return -1
```