5

I have got a code that generates all possible correct strings of balanced brackets. So if the input is n = 4 there should be 4 brackets in the string and thus the answers the code will give are: {}{} and {{}}.

Now, what I would like to do is print the number of possible strings. For example, for n = 4 the outcome would be 2.

Given my code, is this possible and how would I make that happen?

checkmate_
  • 51
  • 3
  • Maybe just count the number of " " spaces in your output string? The answer would be the number of spaces + 1. – gstukelj Oct 08 '19 at 12:39
  • 1
    `void main()` -> `int main()` – Ed Heal Oct 08 '19 at 12:52
  • 1
    Your function is flawed in that you do not check the parameters, any of the parameters could supplied as negative, change your parameters to unsigned. check p before use is < than the sizeof str. – SPlatten Oct 08 '19 at 12:58

2 Answers2

2

Just introduce a counter.

// Change prototype to return the counter
int findBalanced(int p,int n,int o,int c)
{
    static char str[100];

    // The counter
    static int count = 0;
    if (c == n) {
        // Increment it on every printout
        count ++;
        printf("%s\n", str);
        // Just return zero. This is not used anyway and will give
        // Correct result for n=0
        return 0;
    } else {
        if (o > c) {
            str[p] = ')';
            findBalanced(p + 1, n, o, c + 1);
        }
        if (o < n) {
            str[p] = '(';
            findBalanced(p + 1, n, o + 1, c);
        }
    }
    // Return it
    return count;
}
klutt
  • 30,332
  • 17
  • 55
  • 95
1

What you're looking for is the n-th Catalan number. You'll need to implement binomial coefficient to calculate it, but that's pretty much it.

gstukelj
  • 2,291
  • 1
  • 7
  • 20