Problem
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example
given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Algorithm
整理一下题意:给定n对括号,要求返回所有对于这些括号的有效组合。
设left,right分别表示剩余的左括号和有括号数量。当left和right都为0,表示所有括号都组合完成,可以加入到结果向量中。
左括号加入的条件是left>0。
右括号加入的条件是right>0。由于右括号需要与左括号匹配,所以加入的右括号数量应该小于左括号数量,对于剩余的括号数量来说,就是right>left。
编写代码时考虑到一个问题,加入(和加入)的前后顺序可能导致部分情况丢失,如果避免这样的错误。这里采用的方法是使函数返回void。由于在left和right的判断中都没有直接return 的情况,所以可以使所有情况得到遍历。
代码如下。
//用时3ms
class Solution {
public:
vector<string> generateParenthesis(int n) {
int left=n,right=n;
string temp;
vector<string> result;
generate(left,right,temp,result);
return result;
}
void generate(int left,int right,string temp, vector<string>&result)
{
if(left==0&&right==0) result.push_back(temp);
if(left>0) generate(left-1,right,temp+'(',result);
if(right>0&&left<right) generate(left,right-1,temp+')',result);
}
};