N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
和上题几乎一样,还简单点。
1 class Solution { 2 private: 3 int res; 4 public: 5 int totalNQueens(int n) { 6 vector state(n, -1); 7 res = 0; 8 helper(state, 0); 9 return res;10 }11 void helper(vector &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 &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 };