LeetCode: N-Queens II

来源:互联网 发布:域名可以自建吗 编辑:程序博客网 时间:2024/04/28 18:28

Follow up for N-Queens problem.

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

递归解法:

class Solution {public:    bool check(int row, int* place)    {        for (int i = 0; i < row; ++i)        {            int diff = abs(place[i] - place[row]);            if (diff == 0 || diff == row - i)                return false;        }        return true;    }        void placeQueens(int row, int n, int &count, int* place)    {        if (row == n)        {            ++count;            return;        }                for (int i = 0; i < n; ++i)        {            place[row] = i;            if (check(row, place))                placeQueens(row+1, n, count, place);        }    }        int totalNQueens(int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        int* place = new int[n];        int count = 0;        placeQueens(0, n, count, place);        return count;    }};


原创粉丝点击