

#yyds干货盘点# LeetCode 热题 HOT 100:括号生成
source link: https://blog.51cto.com/u_13321676/5691617
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

#yyds干货盘点# LeetCode 热题 HOT 100:括号生成
精选 原创数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
输入:n = 1
输出:["()"]
代码实现:
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<String>();
backtrack(ans, new StringBuilder(), 0, 0, n);
return ans;
}
public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max) {
if (cur.length() == max * 2) {
ans.add(cur.toString());
return;
}
if (open < max) {
cur.append('(');
backtrack(ans, cur, open + 1, close, max);
cur.deleteCharAt(cur.length() - 1);
}
if (close < open) {
cur.append(')');
backtrack(ans, cur, open, close + 1, max);
cur.deleteCharAt(cur.length() - 1);
}
}
}
- 赞
- 收藏
- 评论
- 分享
- 举报
Recommend
-
6
#yyds干货盘点# LeetCode 热题 HOT 100:两数相加 精选 原创 灰太狼_cxh 2022-09-...
-
4
#yyds干货盘点# LeetCode 热题 HOT 100:两数之和 精选 原创 灰太狼_cxh 2022-09-...
-
4
#yyds干货盘点# LeetCode 热题 HOT 100:四数之和 精选 原创 灰太狼_cxh 2022-09-...
-
9
#yyds干货盘点# LeetCode 热题 HOT 100: 有效的括号 精选 原创 灰太狼_cxh 2022-...
-
10
#yyds干货盘点# LeetCode 热题 HOT 100:最长有效括号 精选 原创 灰太狼_cxh 2022...
-
5
#yyds干货盘点# LeetCode 热题 HOT 100:接雨水 精选 原创 灰太狼_cxh 2022-09-27...
-
5
#yyds干货盘点# LeetCode 热题 HOT 100:全排列 精选 原创 灰太狼_cxh 2022-09-27...
-
8
#yyds干货盘点# LeetCode 热题 HOT 100:最大子数组和 精选 原创 灰太狼_cxh 2022...
-
5
#yyds干货盘点# LeetCode 热题 HOT 100:跳跃游戏 精选 原创 灰太狼_cxh 2022-09-...
-
3
#yyds干货盘点# LeetCode 热题 HOT 100:爬楼梯 精选 原创 灰太狼_cxh 2022-10-08...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK