[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);
        }
    }
}

你可能感兴趣的:(zenefits,string,递归,backtracking,recursion)