产生Parentheses

本文介绍了一种使用递归算法生成所有有效括号组合的方法。针对给定数量的成对括号,通过递归调用确保左括号始终不小于右括号的数量,并在两者数量相等时记录有效组合。

Leet Code上的题

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

可以利用递归的思想进行求解,当‘(’的个数大于等于‘)‘的个数时,可以添加‘)‘;最后当‘(’的个数和‘)‘的个数都=0时,打印。

代码如下:

void printPar(int L, int R, vector<string>& result, char* str, int idx)  
    {  
        if (L < 0 || R < L) return;  
        if (L == 0 && R == 0)  
        {  
            str[idx] = '\0';  
            result.push_back(string(str));  
        }  
        else  
        {  
            if (L > 0)  
            {  
                str[idx] = '(';  
                printPar(L-1, R, result, str, idx+1);  
            }  
            if (R > L)  
            {  
                str[idx] = ')';  
                printPar(L, R-1, result, str, idx+1);  
            }  
        }  
    }   
    vector<string> generateParenthesis(int n) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        vector<string> result;  
        char* str = new char[2*n+1];  
        printPar(n, n, result, str, 0);  
        delete []str;  
        return result;  
    } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值