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));
}- A. 4
- B. 6
- C. 5
- 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
- What is printed? c #include <stdio.h> #include <stdlib.h> int cmp(const void a, const void b) { return (const unsigned char )a - (const…
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0xFF & ~0x1Cu; printf("%u", x); }
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0x0F; x |= 0x40; x &= ~1u; printf("%u", x); }
- What is printed? Assume int is 4 bytes with 4-byte alignment. c #include <stdio.h> union U { char c[5]; int i; }; int main(void) {…
- What is printed? c #include <stdio.h> #include <string.h> int main(void) { printf("%d", strcmp("apple", "apricot") < 0); }
- How many times does the letter a occur in "panda"? The program counts with recursion. c #include <stdio.h> int cnt(const char s) { if (s…