22
08/2015
[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; } } };
转载请注明:康瑞部落 » [LeetCode] N-Queens II
0 条评论