3道题目
332. 重新安排行程
51. N 皇后
37. 解数独
解题理解
今天的题目都很难,只是看了下思路
332
Python的题解好像只有一个不超时的
from collections import defaultdict
class Solution:
def findItinerary(self, tickets):
targets = defaultdict(list) # 创建默认字典,用于存储机场映射关系
for ticket in tickets:
targets[ticket[0]].append(ticket[1]) # 将机票输入到字典中
for key in targets:
targets[key].sort(reverse=True) # 对到达机场列表进行字母逆序排序
result = []
self.backtracking("JFK", targets, result) # 调用回溯函数开始搜索路径
return result[::-1] # 返回逆序的行程路径
def backtracking(self, airport, targets, result):
while targets[airport]: # 当机场还有可到达的机场时
next_airport = targets[airport].pop() # 弹出下一个机场
self.backtracking(next_airport, targets, result) # 递归调用回溯函数进行深度优先搜索
result.append(airport) # 将当前机场添加到行程路径中
51
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
board = ['.' * n for _ in range(n)]
self.backtracking(n, 0, board, res)
return [[''.join(row) for row in result] for result in res]
def backtracking(self, n, row, board, res):
if row == n:
res.append(board[:])
return
for col in range(n):
if self.isValid(row, col, board):
board[row] = board[row][:col] + 'Q' + board[row][col + 1:]
self.backtracking(n, row + 1, board, res)
board[row] = board[row][:col] + '.' + board[row][col + 1:]
def isValid(self, row, col, board):
for i in range(row):
if board[i][col] == 'Q':
return False
i = row - 1
j = col - 1
while i >= 0 and j >= 0:
if board[i][j] == 'Q':
return False
i -= 1
j -= 1
i = row - 1
j = col + 1
while i >= 0 and j < len(board):
if board[i][j] == 'Q':
return False
i -= 1
j += 1
return True
37
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.backtracking(board)
def backtracking(self, board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] != '.':
continue
for k in range(1, 10):
if self.isValid(board, i, j, k):
board[i][j] =str(k)
if self.backtracking(board): return True
board[i][j] = '.'
return False
return True
def isValid(self, board, row, col, val):
for i in range(9):
if board[i][col] == str(val):
return False
for j in range(9):
if board[row][j] == str(val):
return False
start_row = (row // 3) * 3
start_col = (col // 3) * 3
for i in range(start_row, start_row + 3):
for j in range(start_col, start_col + 3):
if board[i][j] == str(val):
return False
return True