用C++写一个数字 n 代表生成括号的对数,用于能够生成所有可能的并且 有效的 括号组合的程序
时间: 2024-05-03 16:21:37 浏览: 68
括号配对的小程序c++栈
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void generateParenthesis(int n, char** result, int* returnSize) {
if (n <= 0) {
return;
}
char* str = (char*)malloc(sizeof(char) * (2 * n + 1));
memset(str, 0, sizeof(char) * (2 * n + 1));
int left = n, right = n;
int pos = 0;
generate(str, left, right, pos, result, returnSize);
free(str);
}
void generate(char* str, int left, int right, int pos, char** result, int* returnSize) {
if (left == 0 && right == 0) {
result[*returnSize] = (char*)malloc(sizeof(char) * (strlen(str) + 1));
strcpy(result[*returnSize], str);
(*returnSize)++;
return;
}
if (left > 0) {
str[pos] = '(';
generate(str, left - 1, right, pos + 1, result, returnSize);
}
if (right > left) {
str[pos] = ')';
generate(str, left, right - 1, pos + 1, result, returnSize);
}
}
int main() {
int n = 3;
int returnSize = 0;
char** result = (char**)malloc(sizeof(char*) * 1000);
generateParenthesis(n, result, &returnSize);
printf("All valid combinations of %d pairs of parentheses:\n", n);
for (int i = 0; i < returnSize; i++) {
printf("%s\n", result[i]);
free(result[i]);
}
free(result);
return 0;
}
```
阅读全文