codekofi
← All problems

Problem 19

Medium40 XP

1 · Worked examples

0 / 3

Give it an input and say what you think comes back. It compiles and runs for real, so a wrong guess still shows you the answer — probe as much as you like. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1void build(int open, int close, string& current,
2 vector<string>& out) {
3 if (open == 0 && close == 0) {
4 out.push_back(current);
5 return;
6 }
7
8 if (open > 0) {
9 current.push_back('(');
10 build(open - 1, close + 1, current, out);
11 current.pop_back();
12 }
13 if (close > 0) {
14 current.push_back(')');
15 build(open, close - 1, current, out);
16 current.pop_back();
17 }
18}
19
20vector<string> solution(int n) {
21 vector<string> out;
22 string current;
23 build(n, 0, current, out);
24 return out;
25}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.