2014年2月12日星期三

LeetCoder - 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:

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

public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> ret = new ArrayList<String>();
        if(n<=0) {
            return ret;
        }
        getPara(n, n, "", ret);
        return ret;
    }
    
    public void getPara(int left, int right, String s, ArrayList<String> ret) {
        if(left==0 && right==0) {
            ret.add(s);
        }
        if(right>left) {
            getPara(left, right-1, s + ")", ret);
        }
        if(left>0) {
            getPara(left-1, right, s = s + "(", ret);
        }
    }

}

没有评论:

发表评论