Leetcode: Generate Parentheses

本文介绍了一种使用递归生成所有合法括号组合的方法,包括核心算法实现和具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

又是把所有满足条件的结果存到一个ArrayList里面, 之前也有类似的如Letter combination of a Phone Number这道题。这种类型的题其实形成了一个套路,套路就是,recursion参数包括最终结果的集合(ArrayList),input(String),递归层次level(int),某一条具体的路径Path

Code Ganker的做法,高手的代码就是简洁啊

 1 public ArrayList<String> generateParenthesis(int n) {
 2     ArrayList<String> res = new ArrayList<String>();
 3     if(n<=0)
 4         return res;
 5     helper(n,n,new String(),res);
 6     return res;
 7 }
 8 private void helper(int l, int r, String item, ArrayList<String> res)
 9 {
10     if(r<l)
11         return;
12     if(l==0 && r==0)
13     {
14         res.add(item);
15     }
16     if(l>0)
17         helper(l-1,r,item+"(",res);
18     if(r>0)
19         helper(l,r-1,item+")",res);
20 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值