Skip to content

Commit b14fa66

Browse files
committed
Added recursion solutions: Regular Expression Matching and N-Queens
1 parent 214fdad commit b14fa66

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

C++/N-queens.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Solution {
5+
public:
6+
vector<vector<string>> result;
7+
8+
void solve(int n, int row, vector<string> &board,
9+
vector<bool> &cols, vector<bool> &d1, vector<bool> &d2) {
10+
if (row == n) {
11+
result.push_back(board);
12+
return;
13+
}
14+
15+
for (int col = 0; col < n; col++) {
16+
if (cols[col] || d1[row - col + n - 1] || d2[row + col]) continue;
17+
18+
board[row][col] = 'Q';
19+
cols[col] = d1[row - col + n - 1] = d2[row + col] = true;
20+
21+
solve(n, row + 1, board, cols, d1, d2);
22+
23+
board[row][col] = '.';
24+
cols[col] = d1[row - col + n - 1] = d2[row + col] = false;
25+
}
26+
}
27+
28+
vector<vector<string>> solveNQueens(int n) {
29+
vector<string> board(n, string(n, '.'));
30+
vector<bool> cols(n), d1(2*n - 1), d2(2*n - 1);
31+
solve(n, 0, board, cols, d1, d2);
32+
return result;
33+
}
34+
};
35+
36+
int main() {
37+
Solution sol;
38+
auto ans = sol.solveNQueens(4);
39+
for (auto &board : ans) {
40+
for (auto &row : board)
41+
cout << row << endl;
42+
cout << "------" << endl;
43+
}
44+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
class Solution {
5+
public:
6+
bool isMatch(string s, string p) {
7+
if (p.empty()) return s.empty();
8+
9+
bool firstMatch = (!s.empty() && (s[0] == p[0] || p[0] == '.'));
10+
11+
if (p.size() >= 2 && p[1] == '*') {
12+
// Two options: skip the pattern or use it if matches
13+
return (isMatch(s, p.substr(2)) ||
14+
(firstMatch && isMatch(s.substr(1), p)));
15+
}
16+
else {
17+
return firstMatch && isMatch(s.substr(1), p.substr(1));
18+
}
19+
}
20+
};
21+
22+
int main() {
23+
Solution sol;
24+
cout << boolalpha << sol.isMatch("aab", "c*a*b") << endl; // true
25+
}

0 commit comments

Comments
 (0)