Problem

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

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        helper(0, 0, n, "", res);
        return res;
    }
    private void helper(int left, int right, int total, String str, List<String> res) {
        if (str.length() == total*2) {
            res.add(str);
            return;
        }
        if (left < total) {
            helper(left+1, right, total, str+"(", res);
        }
        if (right < left) {
            helper(left, right+1, total, str+")", res);
        }
    }
}

linspiration
161 声望53 粉丝