52. N-Queens II

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],

["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]

class Solution:
    def totalNQueens(self, n):
        """
        :type n: int
        :rtype: List[List[str]]
        """
        board = [-1] *n
        count = 0
        def safe(a,b):
            for i in range(a):
                if board[i]==b or abs(board[i]-b)==abs(a-i):
                    return False
            return True
        def dfs(line):
            nonlocal count
            if line == n:
                count += 1
                return
            else:
                for i in range(n):
                    if safe(line,i):
                        board[line] = i
                        dfs(line + 1)
        dfs(0)
        return count

关键子nonlocal的作用与关键字global类似,使用nonlocal关键字可以在一个嵌套的函数中修改嵌套作用域中的变量

原文地址:https://www.cnblogs.com/bernieloveslife/p/9734832.html