[LeetCode 22] Generate Parentheses
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Diffculty
Easy
Similar Problems
[LeetCode ] Letter Combinations of a Phone Number Medium
[LeetCode ] Valid Parentheses Easy
Analysis
通过不断插入 "(" 和 ")" 直到两者的数量都为 n ,则一个 combination 构建完成(递归终止条件)。如何保证这个 combination 是 well-formed ?在插入过程中的任何时候:
1、只要 "(" 的数量没有超过 n,都可以插入 "("。 2、而可以插入 ")" 的前提则是当前的 "(" 数量必须要多余当前的 ")" 数量。
Solutions
1、递归
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> allComb;
string comb;
findParenthesis(n, 0, 0, comb, allComb);
return allComb;
}
void findParenthesis(int n, int nleft, int nright, string &comb, vector<string> &allComb) {
if(nleft == n && nright == n) { // comb.size() == 2 * n
allComb.push_back(comb);
return;
}
if(nleft < n) {
comb.push_back('(');
findParenthesis(n, nleft + 1, nright, comb, allComb);
comb.pop_back();
}
if(nright < nleft) {
comb.push_back(')');
findParenthesis(n, nleft, nright + 1, comb, allComb);
comb.pop_back();
}
}
};
2、递归 DFS
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
generateParenthesisDFS(n, n, "", res);
return res;
}
void generateParenthesisDFS(int left, int right, string out, vector<string> &res) {
if (left > right) return;
if (left == 0 && right == 0) res.push_back(out);
else {
if (left > 0) generateParenthesisDFS (left - 1, right, out + '(', res);
if (right > 0) generateParenthesisDFS (left, right - 1, out + ')', res);
}
}
};