Leetcode: N-Queens II

Follow up for N-Queens problem.

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

用I的vector过不了,用数组速度应该会快一些,再加速一下同一列上是否合法的判断,过了。

class Solution {
public:
    int totalNQueens(int n) {
        int result = 0;
        cols = new int[n];
        used = new bool[n];
        for (int i = 0; i < n; ++i) {
            cols[i] = 0;
            used[i] = false;
        }
        solveNQueensUtil(0, n, result);
        
        delete []cols;
        delete []used;
        return result;
    }
    
    void solveNQueensUtil(int step, int n, int &result) {
        if (step == n) {
            ++result;
            return;
        }
        
        for (int i = 0; i < n; ++i) {
            cols[step] = i;
            if (!used[i] && canPutQueen(step)) {
                used[i] = true;
                solveNQueensUtil(step + 1, n, result);
                used[i] = false;
            }
        }
    }
    
    bool canPutQueen(int step) {
        for (int i = 0; i < step; ++i) {
            if (abs(step - i) == abs(cols[step] - cols[i])) {
                return false;
            }
        }
        
        return true;
    }
    
private:
    int *cols;
    bool *used;
};
网上有个超快的位运算版本,懒得研究了啊。

你可能感兴趣的:(LeetCode)