[LintCode/LeetCode] Generate Parentheses

Problem


Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example


Given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"

Note


By the way,
Symbol
meaning
/t
new tab
/n
new line
/r
return

Solution

public class Solution {
    // @param n n pairs
    // @return All combinations of well-formed parentheses
    public ArrayList generateParenthesis(int n) {
        // Write your code here
        ArrayList res = new ArrayList();
        helper(n, n, new String(), res);
        return res;
    }
    public void helper(int l, int r, String s, List res) {
        
        if (r < l) return; // : , 
        if (l > 0) {
            helper(l-1, r, s+"(", res);
        }
        if (r > 0) {
            helper(l, r-1, s+")", res);
        }
        if (l == 0 && r == 0) { // , s res
            res.add(s);
        }
    }
}

좋은 웹페이지 즐겨찾기