Python Fastest Solution 39ms


  • 0
    Y

    Using bit operation (">>", "<<", "&" and "|") to reduce time on "if" block, and memory cost.

    class Solution(object):
        def totalNQueens(self, n):
            cases = [[0, 0, 0]]
            fil = (1 << n) - 1
    
            for _ in range(n):
                new_cases = []
                for row, ld, rd in cases:
                    ld = (ld << 1) & fil
                    rd = rd >> 1
                    pos = (~(ld | rd | row)) & fil
                    while pos:
                        p = pos & (~pos + 1)
                        pos = pos - p
                        new_cases.append([row + p, ld + p, rd + p])
                cases = new_cases
    
            return len(cases)
    

Log in to reply
 

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