数数

che*_*te_ 5 brackets counting

我有一个代码,可以生成所有可能的正确的平衡括号字符串。因此,如果输入为n = 4,则字符串中应该有4个括号,因此代码给出的答案是:{} {}和{{}}。

现在,我想做的是打印可能的字符串数。例如,对于n = 4,结果将为2。

鉴于我的代码,这可能吗,我将如何实现?

klu*_*utt 2

只需引入一个计数器即可。

// 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;
}
Run Code Online (Sandbox Code Playgroud)