[LeetCode]N-Queens II

N-Queens II

Follow up for N-Queens problem.

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

 

和上题N-Queens几乎一样,还简单点。

 1 class Solution {
 2 private:
 3   int res;
 4 public:
 5   int totalNQueens(int n) {
 6     vector<int> state(n, -1);
 7     res = 0;
 8     helper(state, 0);
 9     return res;
10   }
11   void helper(vector<int> &state, int row)
12   {
13     int n = state.size();
14     if(row == n)
15     {
16       res++;
17       return;
18     }
19     for(int col = 0; col < n; col++)
20       if(isValid(state, row, col))
21       {
22         state[row] = col;
23         helper(state, row+1);
24         state[row] = -1;
25       }
26   }
27   bool isValid(vector<int> &state, int row, int col)
28   {
29     for(int i = 0; i < row; i++)
30       if(state[i] == col || abs(row - i) == abs(col - state[i]))
31         return false;
32     return true;
33   }
34 
35 };

 

posted @ 2015-09-06 00:00  Sean_le  阅读(121)  评论(0编辑  收藏  举报