-
Notifications
You must be signed in to change notification settings - Fork 1
/
034.cpp
53 lines (47 loc) · 1.25 KB
/
034.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
034. N-Queens II
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Have you met this question in a real interview?
Example
For n=4, there are 2 distinct solutions.
*/
class Solution {
public:
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
vector<int> state(n, -1);
res = 0;
helper(state, 0);
return res;
}
private:
int res;
void helper(vector<int>& state, int row) {
int n = state.size();
if(row == n) {
res++;
return;
}
for(int col = 0; col < n; col++) {
if(isValid(state, row, col)) {
state[row] = col;
helper(state, row+1);
state[row] = -1;;
}
}
}
bool isValid(vector<int>& state, int row, int col) {
for(int i = 0; i < row; i++) {
if(state[i] == col || abs(row - i) == abs(col - state[i])) {
return false;
}
}
return true;
}
};