Skip to content

Commit deb3952

Browse files
authored
Merge pull request larissalages#119 from PriyanshVerma/master
add N Queens (51.cpp)
2 parents 0fb69f6 + a715c00 commit deb3952

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed

leetcode/cpp/backtracking/51.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#define f first
2+
#define s second
3+
class Solution {
4+
private:
5+
int n;
6+
vector<string> board;
7+
vector<vector<string>> res;
8+
9+
void solve(int row) {
10+
if (row == n) {
11+
res.push_back(board);
12+
return;
13+
}
14+
15+
for (int col = 0; col < n; ++col)
16+
{
17+
board[row][col] = 'Q';
18+
if (valid(row, col)) {
19+
solve(row+1);
20+
}
21+
board[row][col] = '.';
22+
}
23+
}
24+
25+
bool valid(int ROW, int COL) {
26+
vector<pair<int,int>> dirs =
27+
{{-1,-1}, {-1,0}, {-1,1},
28+
{0, -1}, {0,1},
29+
{1, -1}, {1, 0}, {1,1}};
30+
for (auto d: dirs) {
31+
int k = 1;
32+
int nr = ROW + k*d.f, nc = COL + k*d.s;
33+
while (nr < n && nc < n && nr >= 0 && nc >= 0) {
34+
if (board[nr][nc] == 'Q')
35+
return false;
36+
k++;
37+
nr = ROW + k*d.f;
38+
nc = COL + k*d.s;
39+
}
40+
}
41+
42+
return true;
43+
}
44+
45+
public:
46+
vector<vector<string>> solveNQueens(int n) {
47+
this->n = n;
48+
this->board = vector<string> (n, string (n, '.'));
49+
solve(0);
50+
return res;
51+
}
52+
};

leetcode/cpp/string/567.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public:
3+
bool checkInclusion(string sml, string lrg) {
4+
if (lrg.length() < sml.length())
5+
return false;
6+
7+
unordered_map<char, int> targetMap, haveMap;
8+
for(char c: sml) {
9+
targetMap[c]++;
10+
}
11+
12+
for(char c: lrg.substr(0, sml.length())) {
13+
haveMap[c]++;
14+
}
15+
16+
int st=0, en=sml.length()-1;
17+
while(en < lrg.length()) {
18+
if (targetMap == haveMap) {
19+
return true;
20+
}
21+
22+
haveMap[lrg[st]]--;
23+
if (haveMap[lrg[st]]==0) haveMap.erase(lrg[st]);
24+
st++;
25+
en++;
26+
if (en<lrg.length())
27+
haveMap[lrg[en]]++;
28+
}
29+
return false;
30+
31+
}
32+
};

0 commit comments

Comments
 (0)