题目
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队括号
思路
从最左边的”(“开始1个个添加,下1个可能是”)”或者”(“。
记剩余的”(“为left,剩余的”)”为right,有以下情况:
- left = 0, right = 0,所有括号使用完,即找到1个结果。
- left != 0,可以添加”(“。
- right != 0 && left < right,可以添加”)”, 因为肯定先放了”(“才可能再放”)”,所以left < right才能添加”)”。
整个过程图可以参考http://blog.youkuaiyun.com/u012501459/article/details/46787097
代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if (0 == n)
return res;
addParenthesis(res, "", n, n);
return res;
}
void addParenthesis(vector<string> &res, string cur, int left, int right){
if (0 == left && 0 == right){
res.push_back(cur);
return;
}
if (left != 0){
addParenthesis(res, cur+"(", left - 1, right);
}
if (right != 0 && left < right){
addParenthesis(res, cur+")", left, right - 1);
}
}
};