diff --git a/C++/N-queens.cpp b/C++/N-queens.cpp new file mode 100644 index 0000000..585cb3a --- /dev/null +++ b/C++/N-queens.cpp @@ -0,0 +1,44 @@ +#include +using namespace std; + +class Solution { +public: + vector> result; + + void solve(int n, int row, vector &board, + vector &cols, vector &d1, vector &d2) { + if (row == n) { + result.push_back(board); + return; + } + + for (int col = 0; col < n; col++) { + if (cols[col] || d1[row - col + n - 1] || d2[row + col]) continue; + + board[row][col] = 'Q'; + cols[col] = d1[row - col + n - 1] = d2[row + col] = true; + + solve(n, row + 1, board, cols, d1, d2); + + board[row][col] = '.'; + cols[col] = d1[row - col + n - 1] = d2[row + col] = false; + } + } + + vector> solveNQueens(int n) { + vector board(n, string(n, '.')); + vector cols(n), d1(2*n - 1), d2(2*n - 1); + solve(n, 0, board, cols, d1, d2); + return result; + } +}; + +int main() { + Solution sol; + auto ans = sol.solveNQueens(4); + for (auto &board : ans) { + for (auto &row : board) + cout << row << endl; + cout << "------" << endl; + } +} diff --git a/C++/regular-expression-matching.cpp b/C++/regular-expression-matching.cpp new file mode 100644 index 0000000..be21656 --- /dev/null +++ b/C++/regular-expression-matching.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; + +class Solution { +public: + bool isMatch(string s, string p) { + if (p.empty()) return s.empty(); + + bool firstMatch = (!s.empty() && (s[0] == p[0] || p[0] == '.')); + + if (p.size() >= 2 && p[1] == '*') { + // Two options: skip the pattern or use it if matches + return (isMatch(s, p.substr(2)) || + (firstMatch && isMatch(s.substr(1), p))); + } + else { + return firstMatch && isMatch(s.substr(1), p.substr(1)); + } + } +}; + +int main() { + Solution sol; + cout << boolalpha << sol.isMatch("aab", "c*a*b") << endl; // true +}