topic:
brackets. Design an algorithm to print all legal (for example, open and closed one-to-one correspondence) combinations of n pairs of parentheses.
Note: The solution set cannot contain duplicate subsets.
For example, given n = 3, the generated result is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
source:
Interview Question 08.09. Brackets
Problem-solving ideas: backtracking
Define two variables left and right, left records the number of'(', right records the number of')'.
- Recursive termination condition: the left parenthesis must be finished first, so it ends when the right parenthesis is finished
- Recursive call condition: According to the current situation of left and right, determine the possible situation of the next character
public:
vector<string> result;
string path;
vector<string> generateParenthesis(int n) {
back(n, 0, 0);
return result;
}
void back(int n, int left, int right) {
if (right == n) {
// 返回结果
result.push_back(path);
return;
}
// 找出所有可能情况
char cand[2];
int sz = 0;
if (left < n) {
cand[sz++] = '(';
}
if (left > right) {
cand[sz++] = ')';
}
// 处理每种可能情况
for (int i = 0; i < sz; i++) {
path.push_back(cand[i]);
if (cand[i] == '(')
back(n, left+1, right);
else
back(n, left, right+1);
path.resize(path.size() - 1);
}
}
};
Another way of thinking, the code is more concise, as follows:
Two variables, left records the remaining number of left parentheses, and right records the remaining number of right parentheses. There are 2 possible situations:
- Left parenthesis, handle when there is remaining
- The right parenthesis, when the left parenthesis is left, and the left parenthesis is little.
class Solution {
public:
vector<string> result;
string path;
vector<string> generateParenthesis(int n) {
back(n, n);
return result;
}
// left记录左括号剩余数量,right记录右括号剩余数量
void back(int left, int right) {
if (left == 0 && right == 0) {
result.push_back(path);
return;
}
// 无非2种可能情况
if (left > 0) {
// 情况1
path.push_back('(');
back(left-1, right);
path.resize(path.size() - 1);
}
if (left < right && right > 0) {
// 情况2
path.push_back(')');
back(left, right - 1);
path.resize(path.size() - 1);
}
}
};