1

我想打印出 C 中所有有效的 n-paris 括号组合。在主中,我给出一个值 3。那是我想打印出所有有效括号的组合,带有 3 个左括号和 3 个右括号。但是,我遇到了分段错误,gdb 打印到_printValidParentheses(str, leftCount--, rightCount, count++);行。我想知道有人知道我为什么会出错吗?谢谢。

void printString(char * str) {
    while (*str) {
        printf("%c", *str++);
    }
    printf("\n");
}

void _printValidParentheses(char str[], int leftCount, int rightCount, int count) {
    if (leftCount < 0 || rightCount < 0) {
        return;
    }

    if (leftCount == 0 && rightCount == 0) {
        printString(str);
        return;
    } else {
        if (leftCount > 0) {
            str[count] = '(';
            _printValidParentheses(str, leftCount--, rightCount, count++);
        } 

        if (rightCount > leftCount) {
            str[count] = ')';
            _printValidParentheses(str, leftCount, rightCount--, count++);
        }

    }
}

void printValidParentheses(int n) {
    char *str = malloc(sizeof(char) * n * 2);
    _printValidParentheses(str, n, n, 0);
}

int main() {
    printValidParentheses(3);
    return 1;
}
4

1 回答 1

3

您减少/增加此行中的变量:

_printValidParentheses(str, leftCount--, rightCount, count++);

只有在你调用函数之后,你才会得到StackOverflow,因为每次调用函数时都使用相同的参数,并且它会递归地调用自身。

于 2011-12-19T23:03:42.250 回答