Tuesday, February 18, 2014

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:
"((()))", "(()())", "(())()", "()(())", "()()()"
solution: 递归构造字符串。当左括号出现次数<N时,可以放置新的左括号。当右括号出现个数小于左括号出现个数时,就可以放置新的右括号。小破题,但需要对递归思想有很清楚的理解.

Idea: This is a typical problem solved by recursion. The key point is the following rule: when the number of left parentheses is less than N, feel free to put a left parenthesis; Only when the number of right ones is less than the number of left ones,we can put a right parenthesis.
public ArrayList<String> generateParenthesis(int n) {
        
    ArrayList<String> ret = new ArrayList<String>();
    String str = "";
        
    if(n<1) return ret;
        
    getParenthesis(n, n, str, ret);
        
    return ret;
}
    
public void getParenthesis(int numL, int numR, String solution, ArrayList<String> ret){
        
    if(numL==0 && numR==0){
        ret.add(solution);
        return;
    }
        
    if(numL>0){
        getParenthesis(numL-1, numR, solution+"(", ret );
    }
        
    if(numL < numR){
        getParenthesis(numL, numR-1, solution+")", ret );
    }
        
}


No comments:

Post a Comment