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<String> generateParenthesis(int n) {
        // Write your code here
        ArrayList<String> res = new ArrayList<String>();
        helper(n, n, new String(), res);
        return res;
    }
    public void helper(int l, int r, String s, List<String> 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);
        }
    }
}

linspiration
161 声望53 粉丝

引用和评论

0 条评论