Python code, beats 98.16%


  • 0
    S
    class Solution(object):
        def totalNQueens(self, n):
            """
            :type n: int
            :rtype: int
            """
            matrix = []
            res = []
            return dfs(0, [], set(), set(), set(),n )
    
    def dfs(row, path, cols, xySum, xyDif, n):
        res = 0
        if row == n:
            return 1
        for col in range(n):
            if col not in cols and (row+col) not in xySum and (row-col) not in xyDif:
                cols.add(col)
                xySum.add(row+col)
                xyDif.add(row-col)
                res += dfs(row+1, path+[col], cols, xySum, xyDif, n)
                cols.remove(col)
                xySum.remove(row+col)
                xyDif.remove(row-col)
        return res
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.