leetcode #52 in cpp

来源:互联网 发布:二手车估价软件 编辑:程序博客网 时间:2024/04/30 14:35

Follow up for N-Queens problem.

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


This question is simply to calculate how many distinct solution. Since we have already get the distinct solutions from #51. We simply count the valid solutions instead of outputting the board as is done in #51. 

Code: 

class Solution {public:    int totalNQueens(int n) {        vector<int> queen_row_ind;         return solve(n-1,n, queen_row_ind);//start from n-1th column to 0th column    }     int solve(int cur_col,int n, vector<int> &queen_row_ind){        int res = 0;        if(cur_col < 0){            return 1;        }                for(int i = 0; i < n; i ++){            if(isValid(queen_row_ind, i, cur_col, n)){//check if we can put a queen here                queen_row_ind.push_back(i);                res+=solve(cur_col-1, n,queen_row_ind);//calculate distinct solutions                queen_row_ind.pop_back();            }        }        return res;            }        bool isValid(vector<int> &queen_row_ind, int row, int col, int n){        for(int i = 0; i < queen_row_ind.size(); i ++){            int temp_row = queen_row_ind[i];            int temp_col = n-1-i;            //check diag and anti_diag and row            if(abs(temp_row - row) == abs(temp_col - col)|| temp_row == row) return false;        }        return true;            }};

0 0
原创粉丝点击