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 public: 3 int totalNQueens(int n) { 4 vector<int> q(n,-1); 5 int result=0; 6 getQueens(0,n,result,q); 7 return result; 8 } 9 10 void getQueens(int level,int &n,int &result,vector<int> &q) 11 { 12 if(level==n) 13 { 14 result++; 15 return; 16 } 17 bool flag=false; 18 for(int i=0;i<n;i++) 19 { 20 q[level]=i; 21 if(isValid(q,level)) 22 { 23 getQueens(level+1,n,result,q); 24 } 25 q[level]=-1; 26 } 27 } 28 29 30 bool isValid(vector<int> &q,int &level) 31 { 32 33 for(int i=0;i<level;i++) 34 { 35 if(q[i]==q[level]||abs(q[level]-q[i])==abs(level-i)) return false; 36 } 37 38 return true; 39 } 40 41 };