同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
题目为给定一个数字 n ,列出 n 组 ( ) 的所有排列方式。
题目与范例如下
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
解题策略为透过递归 ( Recursion ) , 添加 ' ( ' 与 ' ) ' , 添加 ' ( ' 时检查数目是否过半 ,添加 ' ) ' 时检查是否超过 ' ( ' 的数目。
下方为我的代码
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char **relist;
int total,base;
void RGenerate(char *tempstr,int position,int leftnum,int rightnum,int max){
if(position == max){
tempstr[position] = '\0'; // End String
if(total==base){
base*=2;
relist=realloc(relist,sizeof(char *)*base);
}
relist[total] = (char*)malloc(max+1);
strcpy(relist[total],tempstr);
total++;
}
if(leftnum < (max/2)){
tempstr[position] = '(';
RGenerate(tempstr,position+1,leftnum+1,rightnum,max);
}
if(rightnum<leftnum){
tempstr[position] = ')';
RGenerate(tempstr,position+1,leftnum,rightnum+1,max);
}
}
char ** generateParenthesis(int n, int* returnSize){
total = 0;
base = 8;
relist = (char**)malloc(sizeof(char*)*base);
char *tempstr = (char*)malloc(sizeof(char)*n*2+1);
RGenerate(tempstr,0,0,0,n*2);
(*returnSize) = total;
return relist;
}
下方为时间与空间之消耗
Runtime: 0 ms, faster than 100.00% of C online submissions for Generate Parentheses.
Memory Usage: 6.4 MB, less than 95.68% of C online submissions for Generate Parentheses.