You can use N-Queens I 's method counting for the result. But it wont pass the leetcode test.

Use bit operation will be much faster:

 1 class Solution {
 2 private:
 3     int count, rec;
 4 public:
 5     void getQueen(int row, int ld, int rd) {
 6         if (row == rec) {
 7             count++;
 8             return;
 9         } else {
10             int nonOccupied = rec & ~(row | rd | ld), occupy;
11             while (nonOccupied != 0) {
12                 occupy = nonOccupied & (~nonOccupied + 1);
13                 nonOccupied -= occupy;
14                 getQueen(row + occupy, (ld + occupy) << 1, (rd + occupy) >> 1);
15             }
16         }
17     }
18     int totalNQueens(int n) {
19         count = 0;
20         rec = (1 << n) - 1;
21         getQueen(0, 0, 0);
22         return count;
23     }
24 };

 

posted on 2015-03-21 09:39  keepshuatishuati  阅读(126)  评论(0编辑  收藏  举报