题目链接:https://leetcode.com/problems/generate-parentheses/
两种解法,第一种自己写的,思路容易理解,但是时间比较长;第二种根据
http://blog.csdn.net/makuiyu/article/details/43340283 的代码改写成C语言,思路不好理解,但是时间比较短。
第一种的思路是用递归的办法,对n-1的结果集的每一个字符间的间隔处插入"()",同时去掉重复的结果。比如n=1时,结果集为"()",n=2时就在"()"左边中间右边分别插入"()",得到"(())"和"()()"。第二种的思路参考上边那个博客,但是思路也写的不清楚我也不大懂,跟卡特兰数有关。
方法1:
char** generateParenthesis(int n, int* returnSize) {
char **ret;
if(n==1)
{
char x[3]="()";
ret=(char **)malloc(sizeof(char *));
ret[0]=(char *)malloc(3*sizeof(char));
strcpy(ret[0],x);
*returnSize=1;
}
else
{
char **last;
int flag;
int lastSize,i,j,k,l,len;
ret=(char **)malloc(1000*sizeof(char *));
*returnSize=0;
last=generateParenthesis(n-1,&lastSize);
for(i=0;i<lastSize;i++)
{ //遍历n-1时的每一个结果
len=strlen(last[i]);
for(j=0;j<len+1;j++)
{ //对每一个结果的每个位置插入"()"
char *temp;
temp=(char *)malloc((2*n+1)*sizeof(char));
for(k=0;k<j;k++)
temp[k]=last[i][k];
temp[k++]='(';
temp[k++]=')';
for(;k<len+3;k++) //把'\0'也复制进去
temp[k]=last[i][k-2];
//在当前结果中查找temp是否已经存在
flag=0;
for(l=0;l<*returnSize;l++)
{
if(strcmp(ret[l],temp)==0)
{
flag=1;
break;
}
}
if(flag==0)
{
ret[*returnSize]=(char *)malloc((2*n+1)*sizeof(char));
strcpy(ret[*returnSize],temp);
*returnSize=*returnSize+1;
}
}
}
}
return ret;
}
方法2:
int fun(char *ret[],int *returnSize,char s[],int l,int r)
{
int len=strlen(s);
if(l==0&&r==0)
{
ret[*returnSize]=(char *)malloc(10*sizeof(char));
strcpy(ret[*returnSize],s);
*returnSize=*returnSize+1;
}
if(l>0)
{
strcat(s,"(");
fun(ret,returnSize,s,l-1,r);
}
if(r>0 && l<r)
{
strcat(s,")");
fun(ret,returnSize,s,l,r-1);
}
if(len>0)
s[len-1]='\0';
return 0;
}
char** generateParenthesis(int n, int* returnSize) {
int l,r;
char **ret;
ret=(char **)malloc(10000*sizeof(char *));
char s[100]="";
*returnSize=0;
l=n;
r=n;
fun(ret,returnSize,s,l,r);
return ret;
}