zoukankan      html  css  js  c++  java
  • 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:

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

     1 public class Solution {
     2     ArrayList<String> result = null;
     3     public ArrayList<String> generateParenthesis(int n) {
     4         // Note: The Solution object is instantiated only once and is reused by each test case.
     5         StringBuffer st = new StringBuffer();
     6         result = new ArrayList<String>();
     7         if(n == 0) return result;
     8         getRow(st, n , n, 0);
     9         return result;
    10     }
    11     public void getRow(StringBuffer st, int n, int m, int num){
    12         if(n == 0 && m == 0){
    13             result.add(st.toString());
    14         }
    15         if(n > 0){
    16             st.append('(');
    17             num ++;
    18             getRow(st, n - 1, m, num);
    19             num --;
    20             st.deleteCharAt(st.length() - 1);
    21         }
    22         if(m > 0 && num > 0){
    23             st.append(')');
    24             num --;
    25             getRow(st, n, m - 1, num);
    26             num ++;
    27             st.deleteCharAt(st.length() - 1);
    28         }
    29     }
    30 }

    第三遍:

     1 public class Solution {
     2     public List<String> generateParenthesis(int n) {
     3         List<String> result = new ArrayList<String>();
     4         generate(result, 0, n, n, new StringBuilder());
     5         return result;
     6     }
     7     
     8     public void generate(List<String> result,int cur,int left,int right, StringBuilder sb){
     9         if(left == 0 && right == 0) result.add(sb.toString());
    10         if(left > 0){
    11             StringBuilder sbs = new StringBuilder(sb);
    12             sbs.append('(');
    13             generate(result, cur + 1, left - 1, right, sbs);
    14         }
    15         if(right > 0 && cur > 0){
    16             StringBuilder sbs = new StringBuilder(sb);
    17             sbs.append(')');
    18             generate(result, cur - 1, left, right - 1, sbs);
    19         }
    20     }
    21 }
  • 相关阅读:
    经典的阿里前端笔试题
    Javascript之浏览器兼容EventUtil
    Javascript之对象的创建
    奇妙的CSS之CSS3新特性总结
    前端优化之无阻塞加载脚本
    正则表达式规则与常见的正则表达式
    全端工程师
    最全前端面试问题及答案总结--《转载》
    奇妙的CSS之布局与定位
    关于在django框架里取已登录用户名字的问题
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3371436.html
Copyright © 2011-2022 走看看