正整数 n 代表生成括号的对数,请设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]示例 2:
输入:n = 1
输出:["()"]提示:
- 1 <= n <= 8
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        doGenerate(result, "", 0, 0, n);
        return result;
    }
    private void doGenerate(List<String> result, String curRes, int leftNum, int rightNum, int n) {
        if (leftNum == n && rightNum == n) {
            result.add(curRes);
            return;
        }
        if (leftNum < n) {
            doGenerate(result, curRes + "(", leftNum + 1, rightNum, n);
        }
        if (rightNum < n && rightNum < leftNum) {
            doGenerate(result, curRes + ")", leftNum, rightNum + 1, n);
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion) 
                     
                     
                        
                        