-
Notifications
You must be signed in to change notification settings - Fork 481
/
0052.cpp
42 lines (40 loc) · 954 Bytes
/
0052.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
#include <vector>
using namespace std;
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
int totalNQueens(int n)
{
int res = 0;
vector<int> pos(n, -1);
helper(pos, n, 0, res);
return res;
}
private:
void helper(vector<int>& pos, int n, int row, int& res)
{
if(row == n) res++;
else
{
for(int col = 0; col < n; col++)
{
if(isValid(pos, row, col))
{
pos[row] = col;
helper(pos, n, row + 1, res);
pos[row] = -1;
}
}
}
}
bool isValid(vector<int>& pos, int row, int col)
{
for(int i = 0; i < row; i++)
{
if (pos[i] == col or (row - i) == abs(col - pos[i]))
return false;
}
return true;
}
};