/**
* Note: The returned array must be malloced, assume caller calls free().
*/
bool isValid(char *stack)
{
int i,len = strlen(stack);
int leftCount = 0;
for(i = 0; i < len; i++)
{
if(stack[i] == '(')
{
leftCount++;
}
else
{
if(leftCount > 0)
{
leftCount--;
}
else
{
return false;
}
}
}
return true;
}
void backTarck(int n, int *returnSize, char **returnStr ,int leftNum, int rightNum,char *stack ,int top)
{
if ((rightNum + leftNum) >= 2 * n)
{
// 当前长度已达2n
stack[top] = '\0';
if(isValid(stack))
{
returnStr[*returnSize] = (char*)malloc( sizeof(char) * (top+ 1));
strcpy(returnStr[*returnSize] , stack);
*returnSize = *returnSize + 1;
}
return;
}
if (leftNum < n)
{
stack[top] = '(';
backTarck(n,returnSize,returnStr,leftNum + 1,rightNum,stack,top + 1);
}
if (rightNum < n)
{
stack[top] = ')';
backTarck(n,returnSize,returnStr,leftNum,rightNum + 1,stack,top + 1);
}
}
char** generateParenthesis(int n, int *returnSize)
{
char **returnStr = (char **)malloc(sizeof(char *) * 2000);
char *stack = (char *)malloc(sizeof(char ) * (n * 2 + 1));
*returnSize = 0;
backTarck(n,returnSize,returnStr,0,0,stack,0);
return returnStr;
}
力扣 22. 括号生成(栈)
最新推荐文章于 2022-11-23 11:18:15 发布