Python DFS


  • 0
    class Solution(object):
        def totalNQueens(self, n):
            """
            :type n: int
            :rtype: List[List[str]]
            """
            Solution.count = 0
            self.helper(0, n, [])
            return Solution.count
            
        def helper(self, i, n, temp):
            if i == n:
                Solution.count += 1
            for j in range(n):
                if self.valid(i,j,temp):
                    self.helper(i+1, n, temp+[(i,j)])
                        
        def valid(self,i,j,temp):
            for a, b in temp:
                if b == j:
                    return False
                if i-a == abs(j-b):
                    return False
            return True

Log in to reply
 

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