ProgrammingVery hardCompetitive coding (CP)

How many valid strings of n = 3 pairs of parentheses are there? The program counts them recursively. What is printed?

How many valid strings of n = 3 pairs of parentheses are there? The program counts them recursively. What is printed?
#include <stdio.h>
int count(int open, int close, int n) {
    if (open == n && close == n) return 1;
    int t = 0;
    if (open < n) t += count(open + 1, close, n);
    if (close < open) t += count(open, close + 1, n);
    return t;
}
int main(void) {
    printf("%d", count(0, 0, 3));
}
  1. A. 4
  2. B. 6
  3. C. 5
  4. D. 8

Correct answer: C. 5

The recursion builds only balanced prefixes, and there are Catalan(3) = 5 valid strings of three pairs.

More C Programming questions

Exams that ask this topic