zoukankan      html  css  js  c++  java
  • [LeetCode#22]Generate Parentheses

    The problem: (This prolem include many programming skills in using recursion!!)

    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:

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

    My analysis:

    The key properity behind this problem is :

    At each position, we could place '(' or ')'. And, we should place 6 brackets in total.

    In fact, we follow the same pattern at each position to decide to place a '(' or ')'. 

    So, why not use recursion to solve this problem? We should try to figure out base cases and violation condition.

    1. we must place three '(' brackets and three ')' brackets. 

    2. when the remained right brackets greater than the remained left bracket, the violation happens. (we should stop the recursion along this path.)

    Base case: both three '(' and three ')' were placed.

    Violation case: remainded right brackets > reamined left brackets ===>  (())) The valid placement could not in it. 

    Skills in implementing recursion:

    1. only when reaching the base case, we insert the answer of this recursion path. 

    2. In Java, the String is passed by reference. However, the String is immutable, if we try to change the String, we would create a copy of the String. The original String would keep the same. The net effect is equal to pass the String by value.  (This properity makes it is quit useable for writing recursion)

            if (l > 0) //at each position, we could add "(" or ")". for the same ans, we choose!
                helper(l - 1, r, ans + "(", ret);
            
            if (r > 0)
                helper(l, r - 1, ans + ")", ret);

    Apparently, the value of ans at the same layer would keep the same for both choice. 

    /*
    recursion is very important!!! understand it !!!
    1. what's the recursion rule? at each position, we add "(" or ")"
    2. what's the base case? l == 0 and r == 0
    3. what's the violation case? the existed left brackets larger than right brackets
    */
    
    public class Solution {
        public ArrayList<String> generateParenthesis(int n) {
            ArrayList<String> ret = new ArrayList<String> ();
            
            if (n == 0)
                return ret;
            
            helper(n, n, new String(), ret);
            return ret;
        }
        
        static public void helper(int l, int r, String ans, ArrayList<String> ret) {
            if (l > r) 
            //this is very important!!! the remained left parenthesis should larger than that of right. ((()))) it's invalid
                return;
            
            if (l == 0 && r == 0)
                ret.add(ans);
            
            if (l > 0) //at each position, we could add "(" or ")". for the same ans, we choose!
                helper(l - 1, r, ans + "(", ret);
            
            if (r > 0)
                helper(l, r - 1, ans + ")", ret);
        }
    }
  • 相关阅读:
    代码的未来
    shell脚本中的[]/[[]]区别
    shell脚本判断文件类型
    muduo库安装
    protobuf安装
    讲给普通人听的分布式数据存储(转载)
    Oracle OCCI学习之开篇
    浅谈MySQL索引背后的数据结构及算法(转载)
    5.7版本mysql查询报错:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:...this is incompatible with sql_mode=only_full_group_by
    IDEA启动tomcat报错:java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContext、ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component
  • 原文地址:https://www.cnblogs.com/airwindow/p/4193274.html
Copyright © 2011-2022 走看看