这道题的经典程度无需赘述,请见八皇后问题

第一道 Hard 难度的题,我就给跪了,完全没思路。勉强看懂号称史上最经典的解法,然后将其改写为 c++11。 此处留坑,等我有空来填。


另外,从这道题开始,我开始引入单元测试。自己编写测试用例,尽量做到 code 无死角, 模仿 LeetCode 的检验机制。(用到新兴单元测试框架 Catch)

#include <functional>

class Solution {
public:
    int totalNQueens(int n) {
        int upperlim = (1 << n) - 1, sum = 0;
        std::function<void(int, int, int)> dfs = [&](int row, int l, int r)
        {
            if (row == upperlim) { ++sum; return; }
            for (int cur = upperlim & (~(row|l|r)), pos = 0; cur; dfs(row+pos, (l+pos)<<1, (r+pos)>>1))
            {
                pos = cur & (-cur);
                cur -= pos;
            }
        };
        dfs(0, 0, 0);
        return sum;
    }
};

LeetCode Direct Link