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 }
  • 相关阅读:
    linux signal 处理
    AssetManager asset的使用
    分治法-汉诺塔问题
    WebSocket初探
    分治策略结合递归思想求最大子序列和
    数据库索引的作用和长处缺点
    Android Service 服务(一)—— Service
    YouTube为什么打不开?以及简便的訪问的方法/解决方式!
    winzip15.0注冊码
    CodeForces 398B 概率DP 记忆化搜索
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3371436.html
Copyright © 2011-2022 走看看