首页 > 其他分享 >#yyds干货盘点# LeetCode面试题: 括号生成

#yyds干货盘点# LeetCode面试题: 括号生成

时间:2023-02-22 23:32:10浏览次数:54  
标签:yyds 面试题 generateAll pos current char balance LeetCode result

1.简述:

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

 

示例 1:

输入:n = 3

输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

输入:n = 1

输出:["()"]

2.代码实现:

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;
}
}

标签:yyds,面试题,generateAll,pos,current,char,balance,LeetCode,result
From: https://blog.51cto.com/u_15488507/6079490

相关文章