Embercode
✕
Recursion and BacktrackingQuick quiz

Parentheses

6 questions. Covers Balanced parentheses.

Questions 1 to 5 of 6

  1. 1. What does this program print? ``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"; } ``
  2. 2. What does this program print? Each 1 means valid and each 0 means not valid. ``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"; } ``
  3. 3. This build function is meant to list the valid strings for n = 1, but it prints )( as well as (). What is the bug? ``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(); } } ``
  4. 4. For n = 1 this build function prints (( as a valid string. Which line causes it? ``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(); } } ``
  5. 5. Which of these is a valid arrangement of brackets for n = 2?

5 question(s) left on this page.