leetcode:N-Queens II

来源:互联网 发布:四川禄宏微交易 知乎 编辑:程序博客网 时间:2024/05/21 07:06

Follow up for N-Queens problem.

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

Subscribe to see which companies asked this question

这题的思想和数独是一样的,看一下这个position(数)是否是valid,如果valid就继续往下走一步

class Solution {    private:    bool isValidPosition(int curRow, int tryColoum, vector<int> &auxVtr) {                for (int i=0; i<=curRow; i++)        {            if (auxVtr[i] == tryColoum)                return false;                            if (abs(curRow-i) == abs(tryColoum-auxVtr[i]))                return false;        }                return true;    }    void NQueensHelper(int curRow, int totalNum, vector<int> &auxVtr, int &retVal) {           if (curRow == totalNum)        {            retVal++;            return;        }                for (int tryColoum = 0; tryColoum<totalNum; tryColoum++)        {            if (isValidPosition(curRow, tryColoum, auxVtr))            {                auxVtr[curRow] = tryColoum;                NQueensHelper(curRow+1, totalNum, auxVtr, retVal);                auxVtr[curRow] = -1;            }        }    }    public:    int totalNQueens(int n) {                int retVal = 0;                vector<int> auxVtr(n, -1);                NQueensHelper(0, n, auxVtr, retVal);                return retVal;    }};


0 0