计算C程序中平衡括号的数量

问题描述 投票:1回答:1

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

现在,我想做的是计数,最后打印出可能的字符串数。例如,对于n = 4,可能的字符串数为2。

给出我的代码,这可能吗,我将如何实现?

#include <stdio.h>

void findBalanced(int p,int n,int o,int c);

void main()
{
    int n;
    printf("n:");
    scanf("%d", &n);

    if (n % 2 != 0) {
        printf("%d\n", 0);
    } else {
        n = n / 2;
        if (n > 0) {
            findBalanced(0, n, 0, 0); 
        }
    }
}

void findBalanced(int p,int n,int o,int c)
{
    static char str[100];

    if (c == n) {
        printf("%s\n", str);
        return;
    } 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);
        }
    }
}
c counting parentheses
1个回答
1
投票

只需介绍一个柜台。

// 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.