一.题目要求
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
二.题目难度
中等
三.输入样例
示例 1:
输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
示例 2:
输入:n = 1
输出:[“()”]
提示:
1 <= n <= 8
四.解题思路
解法1:传统循环取条件
解法2:类似二叉树dfs的思想,配合剪枝
五.代码实现
解2:100 80
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
string path;
int leftNum = 0;
int rightNum = 0;
dfs(ans, path, n, leftNum, rightNum);
return ans;
}
void dfs(vector<string>& ans, string& path, int n, int leftNum, int rightNum) {
//符合条件的加入结果
if (leftNum == rightNum && path.size() == 2 * n) {
ans.push_back(path);
return;
}
//出现不符合的停止
if (path.size() == 2 * n || leftNum < rightNum || leftNum > n || rightNum > n)
return;
//选择左括号
path += '(';
dfs(ans, path, n, leftNum + 1, rightNum);
path.pop_back();
//选择右括号
path += ')';
dfs(ans, path, n, leftNum, rightNum + 1);
path.pop_back();
}
};
解1
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
string path;
int leftNum = 0;
int rightNum = 0;
vector<char> kh = {'(', ')'};
dfs(ans, path, kh, n, leftNum, rightNum);
return ans;
}
void dfs(vector<string>& ans, string& path, vector<char> kh, int n,
int leftNum, int rightNum) {
if (leftNum == rightNum && path.size() == 2 * n) {
ans.push_back(path);
return;
}
if (path.size() == 2 * n || leftNum < rightNum || leftNum > n ||
rightNum > n)
return;
for (int i = 0; i < 2; i++) {
path.push_back(kh[i]);
if (kh[i] == '(')
leftNum++;
else
rightNum++;
dfs(ans, path, kh, n, leftNum, rightNum);
if (kh[i] == '(')
leftNum--;
else
rightNum--;
path.pop_back();
}
}
};
六.题目总结
–