[LeetCode] N-Queens II

N-Queens II

 

Follow up for N-Queens problem.

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

解題思路:

這道題與http://blog.csdn.net/kangrydotnet/article/details/47857469類似,用它的第3個方法計算非常快。

class Solution {
public:
    int totalNQueens(int n) {
        if(n<=0){
            return 0;
        }
        int result = 0;
        
        helper(result, n, 0, 0, 0, 0);
        
        return result;
    }
    
    void helper(int& result, int n, int row, int d, int l, int r){
        if(row == n){
            result++;
            return;
        }
        int p = ((1 << n) - 1) & ~(d | l | r);
        int i = 0;
        while(p){
            if(p&1){
                int m = 1<<i;
                helper(result, n, row + 1, d | m, (l | m) << 1, (r | m) >> 1);
            }
            i++;
            p = p>>1;
        }
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章