题目描述:
第一次提交:回溯:
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: def sub(string, p, c): new = [s for s in string] new[p] = c return ''.join(new) def check(i,j,board): for x in range(n): if board[x][j] == "Q": return False for x in [-1,1]: for y in [-1,1]: i1 = i + x j1 = j + y while 0<=i1<n and 0<=j1<n: if board[i1][j1] == "Q": return False else: i1 += x j1 += y return True def backtrack(i,board): if i == n: res.append(board.copy()) return for j in range(n): if check(i,j,board): board[i] = sub(board[i],j,"Q") backtrack(i+1,board) board[i] = sub(board[i], j, ".") return False res = [] board = ["." * n for _ in range(n)] backtrack(0, board) return res
优化:O(N!)
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: res = [] s = "." * n def backtrack(i, tmp,col,z_diagonal,f_diagonal): if i == n: res.append(tmp) return for j in range(n): if j not in col and i + j not in z_diagonal and i - j not in f_diagonal: backtrack(i+1,tmp + [s[:j] + "Q" + s[j+1:]], col | {j}, z_diagonal |{i + j} , f_diagonal |{i - j} ) backtrack(0,[],set(),set(),set()) return res