题目: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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路:
本题主要应用递归方法:
设s为空,left表示左括号的剩余数,right表示右括号的剩余数,当left>0 时,增加“(”,当right > 0 且 left < right时,增加“)”。以n = 3为例,递归过程如下:
- left from 3 to 0, right = 3, s =”(((“;
- left = 0, right from 3 to 0, s = “((()))”;
- push(s);
- left =1, right from 3 to 2, s = “(()”;
- left = 0, right from 2 to 0 , s = “(()())”;
- push(s);
- left = 1, right from 2 to 1, s = “(())”;
- left = 0, right from 1 to 0, s = “(())()”;
- push(s);
- left = 2, right from 3 to 2, s = “()”;
- left form 2 to 0, right = 2, s = “()((“;
- left = 0, right from 2 to 0, s = “()(())”;
- push(s);
- left = 1, right from 2 to 1, s = “()()”;
- left = 0, right from 1 to 0, s = “()()()”;
- push(s);
至此,完成了整个递归过程。代码实现起来比较简单, 如下:
class solution
{
public:
vector<string> generateParenthesis(int n)
{
vector<string> v;
generateParenthesis(v, "", n, n);
return v;
}
private:
void generateParenthesis(vector<string> &v, string s, int left, int right)
{
if (left == 0 && right == 0)
{
v.push_back(s);
}
if (left > 0)
{
generateParenthesis(v, s + "(", left - 1, right);
}
if (right > 0 && left < right)
{
generateParenthesis(v, s + ")", left, right - 1);
}
}
};