题目:https://leetcode-cn.com/problems/generate-parentheses/
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
样例输入与输出:
n = 3
输出:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"]
思路:
代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
string str; str.resize(2*n);
dfs(0, n, str, ans, 0);
return ans;
}
private:
void dfs(int idx, int n, string& str, vector<string>& ans, int l){
if(idx == 2*n){
if(l == 0){
ans.push_back(str);
}
return;
}
str[idx] = '('; dfs(idx+1, n, str, ans, l+1);
if(l)
{str[idx] = ')'; dfs(idx+1, n, str, ans, l-1); }
}
};
原文:https://www.cnblogs.com/patrolli/p/12243205.html