[LeetCode] Generate Parentheses 解题报告

本文提供了一种通过递归生成指定数量的合法括号组合的方法,并详细解释了解题思路和实现过程。

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:
"((()))", "(()())", "(())()", "()(())", "()()()"

» Solve this problem

[解题思路]
典型的递归。一步步构造字符串。当左括号出现次数<n时,就可以放置新的左括号。当右括号出现次数小于左括号出现次数时,就可以放置新的右括号。

[Code]

1:  void CombinationPar(vector<string>& result, string& sample, int deep,   
2: int n, int leftNum, int rightNum)
3: {
4: if(deep == 2*n)
5: {
6: result.push_back(sample);
7: return;
8: }
9: if(leftNum<n)
10: {
11: sample.push_back('(');
12: CombinationPar(result, sample, deep+1, n, leftNum+1, rightNum);
13: sample.resize(sample.size()-1);
14: }
15: if(rightNum<leftNum)
16: {
17: sample.push_back(')');
18: CombinationPar(result, sample, deep+1, n, leftNum, rightNum+1);
19: sample.resize(sample.size()-1);
20: }
21: }
22: vector<string> generateParenthesis(int n) {
23: // Start typing your C/C++ solution below
24: // DO NOT write int main() function
25: vector<string> result;
26: string sample;
27: if(n!= 0)
28: CombinationPar(result, sample, 0, n, 0, 0);
29: return result;
30: }

这题比较简单,没什么可说的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值