6 questions. Covers Balanced parentheses.
Questions 1 to 5 of 6
cpp #include <iostream> #include <string> #include <vector> long long calls = 0; void build(int n, int open, int close, std::string& cur, std::vector<std::string>& out) { calls++; if ((int)cur.size() == 2 * n) { out.push_back(cur); return; } if (open < n) { cur.push_back('('); build(n, open + 1, close, cur, out); cur.pop_back(); } if (close < open) { cur.push_back(')'); build(n, open, close + 1, cur, out); cur.pop_back(); } } int main() { std::vector<std::string> out; std::string cur; build(2, 0, 0, cur, out); std::cout << out.size() << " " << calls << "\n"; }
1
0
cpp #include <iostream> #include <string> bool is_valid(const std::string& s) { int balance = 0; for (char c : s) { balance += (c == '(') ? 1 : -1; if (balance < 0) return false; } return balance == 0; } int main() { std::cout << is_valid("(()())") << " " << is_valid(")(") << "\n"; }
)(
()
cpp void build(int n, int open, int close, std::string& cur, std::vector<std::string>& out) { if ((int)cur.size() == 2 * n) { out.push_back(cur); return; } if (open < n) { cur.push_back('('); build(n, open + 1, close, cur, out); cur.pop_back(); } if (close < n) { cur.push_back(')'); build(n, open, close + 1, cur, out); cur.pop_back(); } }
cur.size() == n
)
close < open
close < n
(
pop_back
open <= n
((
cpp void build(int n, int open, int close, std::string& cur, std::vector<std::string>& out) { if ((int)cur.size() == 2 * n) { out.push_back(cur); return; } if (open <= n) { cur.push_back('('); build(n, open + 1, close, cur, out); cur.pop_back(); } if (close < open) { cur.push_back(')'); build(n, open, close + 1, cur, out); cur.pop_back(); } }
2 * n
5 question(s) left on this page.