数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例:
输入:n = 3
输出:[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Accepted:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string cur;
int open = 0, close = 0;
dfs(res, cur, open, close, n);
return res;
}
vector<string> res;
void dfs(vector<string>& res, string& cur, int open, int close, int n) {
if(cur.size() == n*2) {
if(isValid(cur)) {
res.emplace_back(cur);
return;
}
}
if(open < n) {
cur.push_back('(');
dfs(res, cur, open+1, close, n);
cur.pop_back();
}
if(close < n) {
cur.push_back(')');
dfs(res, cur, open, close+1, n);
cur.pop_back();
}
}
bool isValid(string str) {
stack<char> s;
for(int i = 0; i < str.length(); i++) {
if (str[i] == ')') {
char c = s.size() ? s.top() : '$';
if(s.size()) s.pop();
if(c != '(') return false;
} else {
s.push(str[i]);
}
}
return s.size() == 0;
}
};
Timeout:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<char> s_vec;
for(int i = 0; i < n; i++) {
s_vec.emplace_back('(');
s_vec.emplace_back(')');
}
dfs(0, s_vec.size()-1, s_vec);
return res;
}
vector<string> res;
void dfs(int first, int end, vector<char> s_vec) {
if (first == end && check(s_vec)) {
string tmp = "";
for(auto ch : s_vec) {
tmp += ch;
}
if (!isExisted(res, tmp))
res.emplace_back(tmp);
}
for(int i = first; i <= end; i++) {
swap(s_vec[i], s_vec[first]);
dfs(first+1, end, s_vec);
swap(s_vec[i], s_vec[first]);
}
}
bool check(vector<char> s_vec) {
stack<char> s;
for(auto c:s_vec) {
if((c - ')') == 0) {
char top = s.size() ? s.top() : '#';
if(s.size()) s.pop();
if (top != '(') {
return false;
}
} else {
s.push(c);
}
}
return s.size() == 0;
}
bool isExisted(vector<string> res, string q) {
vector<string>::iterator it;
it = std::find(res.begin(), res.end(), q);
return it != res.end() ? true : false;
}
};