• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: Generate Parentheses

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 }

 

posted @ 2014-06-12 01:55  neverlandly  阅读(421)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3