22 Generate Parentheses

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Solution) using backtracking

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> resultList = new ArrayList<>();
        if (n == 0) return resultList;
        helper(resultList, "", 0, 0, n);
        return  resultList;
    }

    public void helper(List<String> resultList, String s, int open, int close, int max) {
        if (s.length() == max*2) {
            resultList.add(s);
            return;
        }
        if (open < max) helper(resultList, s+"(", open+1, close, max);
        if (close < open) helper(resultList, s+")", open, close+1, max);
    }
}

results matching ""

    No results matching ""