[LeetCode] 22. Generate Parentheses

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 generateParenthesis(int n) {
        List res = new ArrayList<>();
        helper(0, 0, n, "", res);
        return res;
    }
    private void helper(int left, int right, int total, String str, List 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);
        }
    }
}

你可能感兴趣的:(java,dfs,backtracking)