Predict the output
What does this print?
out: list[str] = []
def grow(s: str, opened: int, closed: int, n: int) -> None:
if len(s) == 2 * n:
out.append(s)
return
if opened < n:
grow(s + "(", opened + 1, closed, n)
if closed < opened:
grow(s + ")", opened, closed + 1, n)
grow("", 0, 0, 3)
print(len(out), out[0], out[-1])Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 5 ((())) ()()()
Right: five strings, from fully nested to fully side by side.
The two counters guarantee every finished string is valid, so the run visits only useful branches.
Why not the others?
- B 6 ((())) ()()(). There are five balanced strings for three pairs.
- C 5 ()()() ((())). Trying '(' first puts the nested string first.