22. 括号生成

有效的含义是指的右括号的数量不能超过左括号。
参考官方答案以及评论
1.完全暴力方法
列举出所有的情况,把无效的舍去
class Solution {
public List<String> generateParenthesis(int n) {
List<String> combinations = new ArrayList<String>();
generateAll(new char[2 * n], 0, combinations);
return combinations;
}
public void generateAll(char[] current, int pos, List<String> result) {
if (pos == current.length) {
if (valid(current)) {
result.add(new String(current));
}
} else {
current[pos] = '(';
generateAll(current, pos + 1, result);
current[pos] = ')';
generateAll(current, pos + 1, result);
}
}
public boolean valid(char[] current) {
int balance = 0;
for (char c: current) {
if (c == '(') {
++balance;
} else {
--balance;
}
if (balance < 0) {
return false;
}
}
return balance == 0;
}
}
2.递归的方法
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
dfs(n,"",res,0,0);
return res;
}
//open 代表 ( 的个数 初始值为 0
//close 代表 ) 的个数 初始值为 0
//s 初始值为 "" 空串
void dfs(int n, String s,List<String> res,int open,int close){
//截枝条件 close>open 说明 ) 比(多了 不符合
//并且 ( 个数不能大于n 因为总数2n ()他两加起来是2n
if(open>n||close>open){
return;
}
if(s.length()==2*n){
res.add(s);
return;
}
// ( open+1
dfs(n,s+"(",res,open+1,close);
// ) close+1
dfs(n,s+")",res,open,close+1);
}
}
3 递归实现,通过减少
和二相似,这个是减少的
class Solution {
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
if(n <= 0){
return res;
}
getParenthesis("",n,n);
return res;
}
// left,right 代表左右括号的数量,用一个少一个
private void getParenthesis(String str,int left, int right) {
if(left == 0 && right == 0 ){
res.add(str);
return;
}
if(left == right){
//剩余左右括号数相等,下一个只能用左括号
getParenthesis(str+"(",left-1,right);
}else if(left < right){
//剩余左括号小于右括号,下一个可以用左括号也可以用右括号
if(left > 0){
getParenthesis(str+"(",left-1,right);
}
getParenthesis(str+")",left,right-1);
}
}
}
等同于如下
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
dfs("",res,n,n);
return res;
}
public void dfs(String s,List<String> res,int open,int close){
if(open<0||close<open){
return;
}
if(open==0&&close==0){
res.add(s);
return;
}
dfs(s+"(",res,open-1,close);
dfs(s+")",res,open,close-1);
}
}
参考:https://leetcode.cn/problems/generate-parentheses/solutions/192912/gua-hao-sheng-cheng-by-leetcode-solution/
https://leetcode.cn/u/yu-niang-niang/

浙公网安备 33010602011771号