[LeetCode#22]Generate Parentheses

4938 단어 LeetCode
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);

    }

}

좋은 웹페이지 즐겨찾기