题目:
题解:
class Solution:def solveNQueens(self, n: int) -> List[List[str]]:def generateBoard():board = list()for i in range(n):row[queens[i]] = "Q"board.append("".join(row))row[queens[i]] = "."return boarddef backtrack(row: int):if row == n:board = generateBoard()solutions.append(board)else:for i in range(n):if i in columns or row - i in diagonal1 or row + i in diagonal2:continuequeens[row] = icolumns.add(i)diagonal1.add(row - i)diagonal2.add(row + i)backtrack(row + 1)columns.remove(i)diagonal1.remove(row - i)diagonal2.remove(row + i)solutions = list()queens = [-1] * ncolumns = set()diagonal1 = set()diagonal2 = set()row = ["."] * nbacktrack(0)return solutions