题目连接:Leetcode 022 Generate Parentheses
解题思路:记录当前状态有几个左括号未匹配,每次搜索判断添加左括号和右括号是否合法。长度够了之后,输出括号匹配的状态。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ret;
if (n == 0) return ret;
queue<string> qs;
queue<int> qi;
qs.push("");
qi.push(0);
for (int i = 0; i < 2*n; i++) {
int t = qs.size();
for (int j = 0; j < t; j++) {
string s = qs.front(); qs.pop();
int c = qi.front(); qi.pop();
if (c < n) {
qs.push(s + '(');
qi.push(c + 1);
}
if (2 * c > i) {
qs.push(s + ')');
qi.push(c);
}
}
}
while (!qs.empty()) ret.push_back(qs.front()), qs.pop();
return ret;
}
};