题目描述(Medium)
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:
题目链接
https://leetcode.com/problems/combination-sum-ii/description/
Example 1:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
算法分析
当左括号出现次数<n时,就可以放置新的左括号;当右括号出现次数小于左括号出现次数时,就可以放置新的右括号。当l==n时,做右括号补全。
提交代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
string solution;
dfs(solution, n, 0, 0);
return this->result;
}
private:
vector<string> result;
void dfs(string &solution, int n, int l, int r) {
if (l == n)
{
string s(solution);
this->result.push_back(s.append(n - r, ')'));
return;
}
solution.push_back('(');
dfs(solution, n, l + 1, r);
solution.pop_back();
if (l > r) {
solution.push_back(')');
dfs(solution, n, l, r + 1);
solution.pop_back();
}
}
};