码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]N-Queens II

时间:2015-09-06 01:09:23      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

[LeetCode]N-Queens II

标签:

原文地址:http://www.cnblogs.com/Sean-le/p/4784254.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!