回溯总结篇
回溯是一棵树-for是横向遍历 递归是纵向遍历 唯一的变化是剪枝
深搜+回溯 好难 先按v排序 再递归
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
self.adj={}
tickets.sort(key=lambda x:x[1])
for u,v in tickets:
if u in self.adj:self.adj[u].append(v)
else:self.adj[u]=[v]
self.res=[]
self.dfs('JFK')
return self.res[::-1]
def dfs(self,s):
while s in self.adj and len(self.adj[s])>0:
v=self.adj[s][0]
self.adj[s].pop(0)
self.dfs(v)
self.res.append(s)
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res=[]
chessboard=['.'*n for _ in range(n)]
self.back(n,0,chessboard,res)
return [[''.join(row) for row in s] for s in res]
def back(self,n,row,chessboard,res):
if row==n:
res.append(chessboard[:])
return
for col in range(n):
if self.isvalid(row,col,chessboard):
chessboard[row]=chessboard[row][:col]+'Q'+chessboard[row][col+1:]
self.back(n,row+1,chessboard,res)
chessboard[row]=chessboard[row][:col]+'.'+chessboard[row][col+1:]
def isvalid(self,row,col,chessboard):
for i in range(row):
if chessboard[i][col]=='Q':
return False
i,j=row-1,col-1
while i>=0 and j>=0:
if chessboard[i][j]=='Q':
return False
i-=1
j-=1
i,j=row-1,col+1
while i>=0 and j<len(chessboard):
if chessboard[i][j]=='Q':
return False
i-=1
j+=1
return True
class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
self.back(board)
def back(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(i,j,k,board):
board[i][j]=str(k)
if self.back(board):return True
board[i][j]='.'
return False
return True
def isvalid(self,row,col,val,board):
for i in range(9):
if board[row][i]==str(val):return False
for j in range(9):
if board[j][col]==str(val):return False
starti=(row//3)*3
startj=(col//3)*3
for i in range(starti,starti+3):
for j in range(startj,startj+3):
if board[i][j]==str(val):return False
return True