Leetcode: N-Queens II

Question

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

Show Tags
Show Similar Problems
Have you met this question in a real interview? Yes No
Discuss

My Solution

Get idea from here.

class Solution(object):
    def totalNQueens(self, n):
        """ :type n: int :rtype: int """
        self.res = 0
        columnInRow = [0]*n
        self.helper( n, 0, columnInRow)
        return self.res

    def helper(self, n, row, columnInRow):
        if row==n:
            self.res += 1
            return

        for ind in range(n):
            columnInRow[row] = ind
            if self.check(row,columnInRow):
                self.helper(n, row+1, columnInRow)

    def check(self, row, columnInRow):
        for ind in range(row):
            if columnInRow[ind]==columnInRow[row] or abs(columnInRow[ind]-columnInRow[row])==(row-ind):
                return False
        return True

Another Solution (Bit Manipulation)

Get idea from here.

你可能感兴趣的:(Leetcode: N-Queens II)