首页 > 其他 > 详细

[LeetCode]N-Queens II

时间:2015-09-06 01:07:23      阅读:294      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!