[leetcode] 52. N-Queens II 解题报告

题目链接:https://leetcode.com/problems/n-queens-ii/

Follow up for N-Queens problem.

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


思路:和N-Queens problem一样,这个不需要打印出棋盘,因此还要更简单一些。点击这里看上题的解题报告。

代码如下:

class Solution {
public:
    void DFS(vector<vector<bool>> hash, int n, int index, int& sum)
    {
        if(index >= n)
        {
            sum++;
            return;
        }
        for(int i = 0; i < n; i++)
        {
            if(!hash[0][i+index] && !hash[1][index-i+n] && !hash[2][i])
            {
                hash[0][i+index] = true;
                hash[1][index-i+n] = true;
                hash[2][i] = true;
                DFS(hash, n, index+1, sum);
                hash[0][i+index] = false;
                hash[1][index-i+n] = false;
                hash[2][i] = false;
            }
        }
    }
    int totalNQueens(int n) {
        if(n <= 0)  return 0;
        vector<bool> tem(2*n+1, false);
        vector<vector<bool>> hash(3, tem);
        int sum = 0;
        DFS(hash, n, 0, sum);
        return sum;
    }
};


你可能感兴趣的:(LeetCode,算法,DFS,backtracking,深搜)