Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution { //http://www.matrix67.com/blog/archives/266
public:
int totalNQueens(int n) {
int end=(1<<n)-1; // for n<=32, generate n bits 1 from right
return numQueens(0, 0, 0, end);
}
private:
int numQueens(int row, int ld, int rd, int &end){
if(row==end)
return 1;
int count=0, p, pos=end & (~(row |ld |rd));
while(pos){
p = pos & (-pos);//get rightmost bit with 1 as value
pos = pos - p;
count+=numQueens(row+p, (ld+p)<<1, (rd+p)>>1, end);
}
return count;
}
};