题目
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
思路
这道题是参考了LeetCode上一个解决方案。通过递归,选择“(”或者“)”加到string后面。如果每添加一个“(”,就把要添加的“)”的数目加1,同时要添加的“(”数目减1。每添加一个“)”,就把要添加的“)”的数目减1。直到“(”,“)”的要添加的数都为0。
代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string str = "";
helper(result, str, n, 0); //左括号的计数从n开始,右括号的计数从0开始。因为无论何时添加左括号总是没错的,但是随意添加右括号可能会导致string不正确,所以只有在string中有未配对的左括号的情况下才能添加右括号。
return result;
}
void helper(vector<string> &result, string str, int n, int m) {
if (n==0 && m==0) {
result.push_back(str);
return;
}
if (m>0) {
helper(result, str+")", n, m-1);
}
if (n>0) {
helper(result, str+"(", n-1, m+1);
}
}
};