LeetCode 22括号生成

括号问题一般有两种解法: 一种是通过栈操作,一种是递归。
本体是要:数字 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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值