[leetcode] 52.N-Queens II

来源:互联网 发布:淘宝客网站是什么 编辑:程序博客网 时间:2024/05/16 12:57

题目:Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.
这里写图片描述
题意:这道题与第51道题的不同是,这道题只需要返回一共有多少种可能,依旧采用回溯的方法来完成,只需要稍微改写第52道题的代码即可。
以上。
代码如下:

class Solution {public:    int totalNQueens(int n) {        if(n <= 0)return 0;        else if(n == 1)return 1;        vector<int> QueenInRows;        for(int i = 0; i < n ; i++)            QueenInRows.push_back(i);        return getAllResult(0,QueenInRows);    }    int getAllResult(int i, vector<int>& QueenInRows){        if(i == QueenInRows.size() - 1){//最后一行皇后列的位置判断是否符合要求,符合返回1,不符合返回0.           for(int k = 0; k < i; k++)                if(abs(QueenInRows[k] - QueenInRows[i]) == abs(i-k))return 0;            return 1;        }        int count = 0;        for(int j = i; j < QueenInRows.size(); j++){            swap(QueenInRows[i],QueenInRows[j]);            bool goout = false;            for(int k = 0; k < i; k++){                if(abs(QueenInRows[k] - QueenInRows[i]) == abs(i-k)){                    swap(QueenInRows[i],QueenInRows[j]);                    goout  = true;                    break;                }            }            if(goout)continue;            count += getAllResult(i+1,QueenInRows);//将在这一列上所有可能的解决方案加起来。            swap(QueenInRows[i],QueenInRows[j]);        }        return count;    }};
0 0