codekofi
← All problems

Problem 19

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. 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
4 if (open == 0 && close == 0) {
5 out.push_back(current);
6 return;
7 }
8
9 if (open > 0) {
10 current.push_back('(');
11 build(open - 1, close + 1, current, out);
12 current.pop_back();
13 }
14
15 if (close > 0) {
16 current.push_back(')');
17 build(open, close - 1, current, out);
18 current.pop_back();
19 }
20}
21
22vector<string> solution(int n) {
23
24 vector<string> ans;
25 string current;
26
27 build(n, 0, current, ans);
28
29 return ans;
30}

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.