LeetCode 22. 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:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

解析:
根据给定的数字,产生符合要求的所有括号的组合情况,比如n=3,则返回3对括号的所有合法的组合情况,即每个产生的字符中所有左右括号配对出现。保证在任意时刻,左括号的数量大于等于右括号的数量。
具体思路如下:
1)left大于right(left和right分别表示剩余左右括号的个数),即,临时变量中右括号的数大于左括号的数,则说明出现了“)(”,这是非法情况,返回即可;

2)left和right都等于0说明,临时变量中左右括号数相等,所以将临时变量中的值存入res中;

3)其余的情况是,先放左括号,然后放右括号,然后递归。
整体采用递归的方式,left_count和right_count分别表示当前时刻剩余的左括号和右括号数量。
[cc lang=”C++”]
class Solution {
public:
vector generateParenthesis(int n) {
vector result;
if(n <= 0) { return result; } string current = ""; generate_parenthesis(result, current, n, n); return result; } void generate_parenthesis(vector &result, string current, int left_count, int right_count)
{
if(left_count > right_count)//剩余的左括号数量大于右括号数量,不合法
return;
if(left_count ==0 && right_count ==0)//剩余数量为0,为一个可行解
result.push_back(current);
else
{
if(left_count > 0)//左括号还有剩余
generate_parenthesis(result, current + “(“, left_count -1, right_count);
if(right_count > 0)
generate_parenthesis(result, current + “)”, left_count, right_count -1);
}
}
};
[/cc]

参考:
https://www.cnblogs.com/love-yh/p/7159404.html

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据