LeetCode (力扣) 22. Generate Parentheses (C) - Medium

同步发于 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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值