括号问题一般有两种解法: 一种是通过栈操作,一种是递归。
本体是要:数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
本体思路:
1:如何穷举所有组合?仔细分析这题可以展开成树给定一个深度,然后求所有的叶子节点的值
2:揭发可以用递归的方法,并且记录下来中甲的所有路径,
满足条件的为lefft = n and right = n 保留下来,其余的不考虑。
具体的代码参考:
#define MAX_SIZE 1430
void GenerateP(int left, int right,int n,int index, int* returnSize, char** result,char* str)
{
//char** tmp = (char*)malloc(sizeof(char*)*MAX_SIZE);
if ((left == n) && (right ==n)){
result[*returnSize] = (char*)calloc((2 * n + 1), sizeof(char));
strcpy_s(result[*returnSize], (2 * n + 1), str);
(*returnSize)++;
return;
}
if (left < n)
{
str[index] = '(';
GenerateP(left + 1, right, n, index + 1, returnSize, result, str);
}
if ((right < n) &&(left >right))
{
str[index] = ')';
GenerateP(left, right + 1, n, index + 1, returnSize, result, str);
}
return;
}
char ** generateParenthesis(int n, int* returnSize) {
char *str = (char*)calloc((2 * n + 1), sizeof(char));
char **result = (char **)malloc(sizeof(char *) * MAX_SIZE);
GenerateP(0,0,n,0,returnSize,result,str);
return result;
}